我可以在函数声明(类的一部分)中使用 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
}
}
...所以当一个对象由这个 Object
类组成时,一个随机颜色将被绘制为对象的背景(除非你传递另一种颜色)。
最佳答案
不,你不能。标准明确禁止:
The keyword
this
shall not be used in a default argument of a member function.
(C++11, [dcl.fct.default]/7)
我相信这条规则是有道理的,因为默认参数的初始化发生在调用者的上下文中,而不是被调用者。 (并且在调用者的上下文中可能没有 this
这样的东西,或者它可能是一个不同的对象,这可能会导致混淆。)
一个可能的解决方案就是重载。
Object::fillBg(int color) {
// ...
}
Object::fillBg() {
fillBg(this->color);
}
关于c++ - 在函数声明中使用 "this"(作为默认参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27807215/