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

标签 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
    }

}

...所以当一个对象由这个 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/

相关文章:

c++ - 为什么选择默认模板函数比其专用版本更匹配?

C++:重命名 dll 和库并链接

c++ - 数组( vector )中大于某个值的元素的起始索引和结束索引

c++ - 字符串文字的值类别是什么?

c++ - 为什么 g++ 无法找到已安装的系统包含?

c++ - 这是一个有效的 Copy Ctor 吗?

c++ - 在 c++ 中传递内联临时类需要是 const。如何解决这个问题

C++ 在一个类中实例化一个类。正确的方法?

c++ - 为什么我会收到 glibc 错误?

c++ - 编译 QTermWidget