开发者

question about Scope Resolution Operator in C++?

I am learning C++ and not quite sure about the Scope Resolution Operator. suppose I have the following code: code 1:

class Student {
     int no;
     int semester;
     char grade[M+1];
 public:
     void display() const;
 };

 void Student::display() const {
     cout << "Hi!" << endl;
 }

code 2:

class Student {
     int no;
     int semester;
     char grade[M+1];
 public:
     void display() const{
        cout << "Hi!" << endl;
    }
 };

any differences if I define the display() 开发者_JAVA百科inside its class? if there is no difference, then why should I use the scope resolution operator?


There is one difference - if defined in the class the function behaves as if it were declared as inline. But this is no big deal, and the compiler may well ignore it. The big difference is that for large, multi-file projects, if you make a change to the function body defined in the header, EVERY other file that uses your header will have to be recompiled. Whereas, if you make a change to the function body defined in a .cpp file, then only that file needs to be recompiled. This can and does make a huge difference to real-world projects.


The scope resolution operator allows you to define the function outside the class.
This provides the ability to not expose/abstract your source code implementation from the users of your library. The class declarations are placed in header files and the actual definitions are kept in a cpp file and then only the object files or libraries of the same are provided to the end user.
You can say it provides oneway of protecting intellectual rights though the feature was not designed specifically for it.


Normally you would define the class in the header file and then implement it in the .cpp file. For the compiler to know what function belongs to which class, you use the Scope Resolution Operator, ie ::.

When you place the function directly inside your header like you showed in example two, you need to prefix it with the inline keyword, which tells the compiler to put that entire function inside the code where you are calling it. Normally you do this with very small functions and for speed considerations, using it a lot can lead to code bloat in your exe.


The main reason is that you don't want to clutter up the class definition with all sorts of irrelevant implementation details, like the implementation of a function. When the class is small, with only one or two functions, and the functions are small, with only one or two lines, it's not necessarily a problem, but in real life, putting the function definitions in the class itself very quickly leads to unreadable code; you want to keep the external definition separate from the internal implementation as much as possible. (On large projects, they'll typically be maintained by different people anyway.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜