extern关键字总结

本文详细解析了C++中extern关键字的使用规范及其注意事项,强调了extern与变量定义、重复定义及成员函数定义的关系,并提供了具体的代码示例。

关于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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值