C++ 头文件(十五)--定义成员属性、引用、避免多次包含
2016-09-08 16:09
316 查看
// MyFirst.hpp
//if not define 第一次引用头文件,如果没有定义宏,则进入#ifndef 和 #endif中间的语句
#ifndef MyFirst_hpp
#define MyFirst_hpp
#include <stdio.h>
//(一)头文件常包含的内容
/*
1.函数原型
2.#define const 的符号常量
3.内联函数 inline
4.结构声明
5.类声明
6.模板声明
7.全局变量声明 extern 为声明变量,没有初始化,需要在cpp文件进行初始化才能被其它文件引用
8.静态变量 static
*/
//(1)
void mfunsion();
//(2)
#define k_num 10
const int consta = 20;
//(3)
inline unsigned line(unsigned x) {return x*x;}
//(4)
struct mstruct {
double d;
char c[10];
int i;
};
//(5)
//(6)
template <typename T>
void mtemplate(T &a,T &b) {
auto c = a;
a = b;
b = c;
}
template <typename T>
void mtemplate2(T &a,T &b){
}
//(7)
extern int inta;
extern int ninta;
//(8)
static int statica = 20;
#endif
//if not define 第一次引用头文件,如果没有定义宏,则进入#ifndef 和 #endif中间的语句
#ifndef MyFirst_hpp
#define MyFirst_hpp
#include <stdio.h>
//(一)头文件常包含的内容
/*
1.函数原型
2.#define const 的符号常量
3.内联函数 inline
4.结构声明
5.类声明
6.模板声明
7.全局变量声明 extern 为声明变量,没有初始化,需要在cpp文件进行初始化才能被其它文件引用
8.静态变量 static
*/
//(1)
void mfunsion();
//(2)
#define k_num 10
const int consta = 20;
//(3)
inline unsigned line(unsigned x) {return x*x;}
//(4)
struct mstruct {
double d;
char c[10];
int i;
};
//(5)
//(6)
template <typename T>
void mtemplate(T &a,T &b) {
auto c = a;
a = b;
b = c;
}
template <typename T>
void mtemplate2(T &a,T &b){
}
//(7)
extern int inta;
extern int ninta;
//(8)
static int statica = 20;
#endif
// MyFirst.cpp #include "MyFirst.hpp" #include <iostream> //(7) int inta = 100; int ninta = 9999;
// main.cpp #include <iostream> #include "MyFirst.hpp" //#include "MyFirst.cpp" using namespace std; int tt; int main(int argc, const char * argv[]) { int d = 10; int c = 20; int & a = d; int & k = c; //引用头文件函数模板 mtemplate2(a, k); d = consta; //(7)extern 引用头文件全局变量 inta = 10; statica = 300; //静态变量 //(7)extern int ninta; 可以不再次声明,作用域尝试寻找当前往上的相同名字变量,如果不存在就引用 MyFirst的变量 cout << &ninta << endl; int ninta; //这里等于重新定义一个全新的同名变量,与MyFirst的变量是不同的两个变量分别在两个内存中 cout << &ninta << endl; ninta = 222; return 0; }
相关文章推荐
- C\C++小知识: 如何引用一个已经定义过的全局变量 与 全局变量可不可以定义在可被多个.C文件包含的头文件中
- C++ 中避免同一文件被多次引用解决方案
- 在c/c++中如何避免头文件被多次包含?
- 语句include和require的区别是什么?为避免多次包含同意文件,可用?语句来代替他们?
- 关于使用#pragma once与#ifndef ___FILE_NAME__H避免文件被多次包含的区别
- C++使用static的错误:无法解析的外部符号、“static”不应在文件范围内定义的成员函数上使用 .
- C/C++由于头文件重复引入引起的成员或类重复定义的解决办法
- C++头文件多次包含 变量,函数重定义解决方案
- 引用原因.NET下编译C++代码时出现fatal error C1083: 无法打开包含文件:“iostream.h”: No such file or directory错误的解决方法.
- C++ 关于声明,定义,类的定义,头文件作用,防止头文件在同一个编译单元重复引用,不具名空间
- 如何引用一个已经定义过的全局变量 与 全局变量可不可以定义在可被多个.C文件包含的头文件中
- 语句include和require的区别是什么?为避免多次包含同意文件,可用?语句来代替他们?
- 如何引用一个已经定义过的全局变量 与 全局变量可不可以定义在可被多个.C文件包含的头文件中
- C++头文件的重定义问题以及头文件互相包含问题
- c++ 避免头文件重复引用 (pragma once与 #ifndef的区别)【转】
- C/C++中头文件多次包含的问题
- C++ 关于声明,定义,类的定义,头文件作用,防止头文件在同一个编译单元重复引用,不具名空间
- C++模板类的成员函数定义与声明必须在一个头文件中
- 函数放在头文件中被多次包含的重定义问题
- C++头文件定义格式_避免重包含