Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 错误:将“xxx”作为“this”参数传递将丢弃限定符_C++ - Fatal编程技术网

C++ 错误:将“xxx”作为“this”参数传递将丢弃限定符

C++ 错误:将“xxx”作为“this”参数传递将丢弃限定符,c++,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&

谁能告诉我为什么会出现以下代码:

#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”参数传递将丢弃限定符

?

我的打印方法是const,这是我理解的唯一必要的方法。对我来说,f中注释掉的sum方法应该会给出一个错误,但print方法不会。如果有人能向我指出我的误解,那就太好了

const void print()
这毫无意义,你的意思是:

void print() const
这毫无意义,你的意思是:

void print() const

您正在对常量对象调用非常量方法print。const方法不能修改它所调用的对象,这是允许您调用const对象以保留const的唯一成员方法。 const方法在方法参数列表后用const表示:


void print const{cout您正在对const对象调用非const方法print。const方法无法修改调用它的对象,这是允许您调用const对象以保持常量的唯一成员方法。 const方法在方法参数列表后用const表示:


无效打印常量{谢谢你的详细解释,帮助我透过树看到木头。谢谢你的详细解释,帮助我透过树看到木头。酷酷的用户名,兄弟:@VioletGiraffe上次我抬头,长颈鹿不会说话。紫色的可以。总是可以。有人编辑维基!酷酷的用户名,兄弟:@VioletGiraffe上次我抬头,长颈鹿不会说话。紫罗兰会。总是会。有人编辑维基!