为何未修改成员的obj::show()触发const限定符丢弃编译错误?
const对象调用非const成员函数的编译错误分析
示例代码
#include <iostream> #include <string> #include <array> #include <iterator> using namespace std; class obj { public: obj() = default; obj(int i) : i_{i} {} void show() {cout << "addr = " << this << ", i_ = " << i_ << endl;} private: int i_{0}; }; int main () { std::array<obj, 4> o_l {131,223,333,344}; for (auto const & idx : o_l) {idx.show();} return 0; }
编译错误信息
source>: In function 'int main()': <source>:22:45: error: passing 'const obj' as 'this' argument discards qualifiers [-fpermissive] 22 | for (auto const & idx : o_l) {idx.show();} | ~~~~~~~~^~ <source>:12:17: note: in call to 'void obj::show()' 12 | void show() {cout << "addr = " << this << ", i_ = " << i_ << endl;}
问题
obj::show()并未修改任何类成员,为何编译器会做出这样的判定?
解答
C++编译器判断成员函数能否被const对象调用,只看函数是否带有const修饰符,不会去检查函数内部有没有实际修改成员变量。
你在循环中声明的idx是const obj&类型,也就是const对象。而show()函数没有被标记为const成员函数,在C++的规则里,非const成员函数被认为是可能修改类成员的,所以编译器不允许const对象调用这类函数,直接抛出错误。
解决方法就是给show()函数加上const修饰,明确告知编译器这个函数不会修改任何类成员:
void show() const {cout << "addr = " << this << ", i_ = " << i_ << endl;}
添加const后,const对象就能正常调用该函数了。
内容的提问来源于stack exchange,提问作者Ahmed R
相关产品推荐
相关产品推荐

