extern关键字总结

xiaoxiao2021-02-27  283

关于extern关键字总结: 1.extern的变量的原先定义的地方不能有static修饰 2.如果声明是const int,那么extern也必须是extern const int 3.两个.cpp文件不能定义同一个变量名 4.头文件基本可以说是不能定义变量的,否则只要有多个cpp文件包含了该头文件,就一定出错,同理也基本不能定义普通函数 5.发现了一个很坑的地方,每个文件内部都可以定义一次同一个类以及成员函数,但是成员函数必须要包括在类的声明里面,而不能拿出来定义,这样的话c++就很不仗义了呀,更坑的是还允许至多一个文件把成员函数定义到类的声明外面。

/************************************************************************* > File Name: a.cpp > Author: > Mail: > Created Time: Sat 29 Apr 2017 04:36:18 PM CST ************************************************************************/ #include "a.h" class C { public: C(int c); void test(); private: int c; }; C::C(int c) { this->c = c; } void C::test() { c+=2; } void test(); //int c; int main() { test(); cout << d << endl; return 0; } /************************************************************************* > File Name: a.h > Author: > Mail: > Created Time: Sat 29 Apr 2017 05:05:02 PM CST ************************************************************************/ #ifndef _A_H #define _A_H #include <iostream> using namespace std; extern const int d; extern int c; inline int test2() { //cout << c << endl; } /*int test2() { cout << c << endl; //和下面同理 }*/ //int c; //如果有这样的语句,且头文件被多个不同的文件包含,就必定出错 #endif /************************************************************************* > File Name: b.cpp > Author: > Mail: > Created Time: Sat 29 Apr 2017 04:37:40 PM CST ************************************************************************/ #include "a.h" #include <iostream> using namespace std; int c = 12345; class C { C(int c) { this->c = c; } void test() { c++; } private: int c; }; /*C::C(int c) { //如果这个文件也在这儿定义就会发成错误了 this->c = c; }*/ const int d = 10; void test() { cout << c << endl; } #Makefile a : a.o b.o g++ a.o b.o -o a a.o : a.cpp a.h g++ a.cpp -c b.o : b.cpp a.h g++ b.cpp -c clean : rm a.o b.o a
转载请注明原文地址: https://www.6miu.com/read-4412.html

最新回复(0)