在上篇文章《inline的另一用处》中,提到函数实现在类定义中与类定义外的区别。
现在先看个实验:
a.cpp:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13#ifndef TEST_H #define TEST_H class A{ public: int fun(int x){ return (x*x+1000); } }; #endif void tt() { }
b.cpp:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12class A{ public: int fun(int x); }; void tt(); int yy() { tt(); A a; return a.fun(3); }
将它们分别编译后再链接:
显示链接错误,因为b.cpp(b.o)中找不到A::fun(int)的引用。
将以上的a.cpp改为如下所示:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14#ifndef TEST_H #define TEST_H class A{ public: int fun(int x); }; #endif int A::fun(int x){ return (x*x+1000); } void tt() { }
分别编译a.cpp和b.cpp为a.o和b.o后链接,显示链接成功。
这样,第一次链接错误的原因就很明显了。
结论:
在类定义中的类成员函数实现有文件内部作用域,而在类定义外部的类实现有的是全局作用域。
最后
以上就是内向板凳最近收集整理的关于C++:成员函数实现在类定义中与在类定义外的区别的全部内容,更多相关C++:成员函数实现在类定义中与在类定义外内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复