在函数声明中使用"this"(作为默认参数)

ale*_*nst 1 c++

我可以this在函数声明(类的一部分)中使用来指定默认参数吗?

例:

class Object {

    Object::Object(){
        this->color = rand(); //let's pretend that rand() will generate a random integer and that fillBg can draw a color given an integer.
    }

    Object::fillBg(int color = this->color){
        //do stuff
    }

}
Run Code Online (Sandbox Code Playgroud)

...所以当一个对象由这个Object类组成时,随机颜色将被绘制为对象的背景(除非你传递另一种颜色).

Bri*_*ian 7

不,你不能.该标准明确禁止它:

关键字this不得用于成员函数的默认参数.

(C++ 11,[dcl.fct.default]/7)

我相信这个规则是有道理的,因为默认参数的初始化发生在调用者的上下文中,而不是被调用者.(在调用者的上下文中可能没有这样的东西this,或者它可能是一个不同的对象,这可能会引起混淆.)

一种可能的解决方案就是过载.

Object::fillBg(int color) {
    // ...
}

Object::fillBg() {
    fillBg(this->color);
}
Run Code Online (Sandbox Code Playgroud)


dev*_*fan 6

我假设课堂上也有变色,否则一切都没有意义.

答案是否定的,这是不可能的.但你可以使用

Object::fillBg()
{
    fillBg(this->color);
}
Object::fillBg(int color)
{
    //use color
}
Run Code Online (Sandbox Code Playgroud)