C + + member function implementations differ from class definitions in class definitions (using g++ directly under Windows)

Source: Internet
Author: User
Tags class definition

In the other use of inline in the previous article, it is mentioned that the function implementation differs from the class definition in the class definition.

Now let's look at an experiment:

A.cpp:

[CPP]View PlainCopy
    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. void TT ()
    11. {
    12. }


B.cpp:

[CPP]View PlainCopy
    1. Class a{
    2. Public :
    3. int Fun (int x);
    4. };
    5. void TT ();
    6. int yy ()
    7. {
    8. TT ();
    9. A;
    10. return A.fun (3);
    11. }

Compile them and then link them separately:

A link error was displayed because a reference to A::fun (int) could not be found in B.cpp (B.O).

Change the a.cpp above to read as follows:

[CPP]View PlainCopy
    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. }  


Compile a.cpp and b.cpp for A.O and B.O, respectively, to display the link successfully.

Thus, the reason for the first link error is obvious.

Conclusion:

A class member function in a class definition implements a file inner scope, whereas a class implementation outside of a class definition has a global scope.

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

C + + member function implementations differ from class definitions in class definitions (using g++ directly under Windows)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.