C++:成员函数实现在类定义中与在类定义外的差异
发布时间:2021-11-23 15:02:17 所属栏目:教程 来源:互联网
导读:现在先看个实验: a.cpp: #ifndef TEST_H #define TEST_H class A{ public: int fun(int x){ return (x*x+1000); } }; #endif void tt() { } b.cpp: class A{ public: int fun(int x); }; void tt(); int yy() { tt(); A a; return a.fun(3); } 将它们分别编
现在先看个实验: a.cpp: #ifndef TEST_H #define TEST_H class A{ public: int fun(int x){ return (x*x+1000); } }; #endif void tt() { } b.cpp: class 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改为如下所示: #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后链接,显示链接成功。 这样,第一次链接错误的原因就很明显了。 结论: 在类定义中的类成员函数实现有文件内部作用域,而在类定义外部的类实现有的是全局作用域。 ![]() (编辑:PHP编程网 - 黄冈站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |