您的位置:首页 > 编程语言 > C语言/C++

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
//  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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐