C++成员函数实现在类定义中与在类定义外的区别(Windows下直接使用g++)

在上篇文章《inline的另一用处》中,提到函数实现在类定义中与类定义外的区别。

    现在先看个实验:

    a.cpp:

   

[cpp] view plain copy
 
  1. #ifndef TEST_H  
  2. #define TEST_H  
  3. class A{  
  4.     public:  
  5.     int fun(int x){  
  6.     return (x*x+1000);  
  7. }  
  8. };  
  9. #endif  
  10.   
  11. void tt()  
  12. {  
  13. }  


b.cpp:

[cpp] view plain copy
 
  1. class A{  
  2.     public:  
  3.     int fun(int x);  
  4. };  
  5. void tt();    
  6. int yy()    
  7. {    
  8.     tt();   
  9.     A a;  
  10.     return a.fun(3);    
  11. }  
  12.       

将它们分别编译后再链接:

显示链接错误,因为b.cpp(b.o)中找不到A::fun(int)的引用。

将以上的a.cpp改为如下所示:

[cpp] view plain copy
 
  1. #ifndef TEST_H  
  2. #define TEST_H  
  3. class A{  
  4.     public:  
  5.     int fun(int x);  
  6. };  
  7. #endif  
  8. int A::fun(int x){  
  9.     return (x*x+1000);  
  10. }  
  11. void tt()  
  12. {  
  13. }  


    分别编译a.cpp和b.cpp为a.o和b.o后链接,显示链接成功。

    这样,第一次链接错误的原因就很明显了。

    结论:

    在类定义中的类成员函数实现有文件内部作用域,而在类定义外部的类实现有的是全局作用域。

http://blog.csdn.net/tobacco5648/article/details/7651408

原文地址:https://www.cnblogs.com/findumars/p/6143375.html