Default arguments in constructor--C++

六月ゝ 毕业季﹏ 提交于 2019-12-01 13:34:00

You'll need to make the parameter into a reference parameter, you shouldn't try to copy std::cerr. You probably need to specify the default parameter in the header file so that it's visible to all clients of the class.

e.g.

class MyClass {
public:
    MyClass(char*, char*, std::ostream& = std::cerr);
    // ...
};

Default arguments are specifed when the function is declared: the header file in this case.

The header file is where you declare the defaults.

functionname(char *arg1, char* arg2, ostream &arg3 = cerr);

And then in the cpp file you'd simply expect it to be there:

functionname(char *arg1, char* arg2, ostream &arg3) {
}

IE, do NOT put it in the .cpp file.

C++ uses the separate compilation. Each cpp file is compiled separately. If you default values in cpp it will work OK, but this default values will be seen only in cpp file.

When include header file in other files of your project compiler determinates all information it needs from header file. If the defaults values are cpp file, other parts of your project can't look into cpp files, as they may be already compiled. So in almost all cases the default values should be kept in header file.

The other problem you can't put default values in both cpp and h file, as while compiling the cpp file compiler would not be able to choose which defaults values should be used and you will have compilation error.

You solution is (in header file):

class MyClass
{
public:
    MyClass(char*, char*, ostream& = cerr);
...
};

In some rare cases you may specify default values in cpp file, if you want only this file to see and use them while all other parts of the project would not be able to do this. But this happens very rarely.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!