错误:传递' xxx'作为'这个'参数抛弃限定词

时间:2016-10-07 13:26:44

标签: c++

任何人都可以告诉我为什么以下代码:

#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;
}

给出编译错误

  

&#34;错误:传递&#39; const测试&#39;作为&#39;这个&#39;参数丢弃限定符&#34;

我的print()方法是const,这是我必须理解的。对我来说,sum()中的(注释掉的)f()方法应该会出错,但不会出现print()方法。如果有人可以向我指出我误解的地方 - 那会很棒。

2 个答案:

答案 0 :(得分:3)

const void print()

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

void print() const

答案 1 :(得分:3)

您在const对象上调用非const方法print()const方法无法修改它所调用的对象,这是允许在const个对象上调用的唯一一种成员方法(以保持常量) )。 在方法参数列表之后,const方法由const 表示:

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

是的,const void充其量是无用的,只有void都是一样的。