【问题标题】:error: passing 'xxx' as 'this' argument discards qualifiers错误:将“xxx”作为“this”参数传递会丢弃限定符
【发布时间】:2016-10-07 13:26:44
【问题描述】:

谁能告诉我为什么下面的代码:

#include <iostream>
using namespace std;

class Test {
    int a, b, c;
public:
    Test() : a(1), b(2), c(3) {}
    const void print() {cout << a << b << c;}
    int sum() {return (a+b+c);}
};

const Test& f(const Test& test) {
    test.print();
    // cout << test.sum();
    return test;
}

main() {
    Test x;
    cout << "2: ";
    y = f(x);
    cout << endl;
}

给出编译错误

“错误:将 'const Test' 作为 'this' 参数传递会丢弃限定符”

?

我的print() 方法是const,这是我所理解的所有必要条件。对我来说,f() 中的(已注释掉的)sum() 方法应该会出错,但 print() 方法不会。如果有人能指出我误解的地方 - 那太好了。

【问题讨论】:

    标签: c++


    【解决方案1】:

    您正在对 const 对象调用非 const 方法 print()const 方法不能修改它所调用的对象,这是您可以在 const 对象上调用的唯一一种成员方法(以保持 const 性)。 一个 const 方法由 const 表示 方法参数列表:

    void print() const {cout &lt;&lt; a &lt;&lt; b &lt;&lt; c;}

    是的,const void 充其量是没用的,只是 void 是一样的。

    【讨论】:

    • 感谢您的详细解释,并帮助我从树林中看到了树林。
    【解决方案2】:
    const void print()
    

    这没有意义,你的意思是:

    void print() const
    

    【讨论】:

    • 酷用户名,兄弟:)
    • @VioletGiraffe 最后我抬头一看,长颈鹿不会说话。
    • 紫色的可以。总是可以的。有人编辑 wiki!
    猜你喜欢
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多