c – 带有const关键字的代码将无法编译
发布时间:2020-12-16 09:59:44 所属栏目:百科 来源:网络整理
导读:我不明白为什么这段代码不会编译. 我在行返回源 – GetA();中得到以下错误 cannot convert ‘this’ pointer from ‘const class FooStruct’ to ‘class FooStruct ’ 如果我删除const关键字,它编译得很好. class FooStruct{ int a;public: int GetA() {ret
我不明白为什么这段代码不会编译.
我在行返回源 – > GetA();中得到以下错误
如果我删除const关键字,它编译得很好. class FooStruct { int a; public: int GetA() {return a;}; int Bar(const FooStruct *source); }; int FooStruct::Bar(const FooStruct *source) { return source->GetA(); } 代码本身没有意义.它已从一些真正的代码中删除,其唯一目的是说明问题. 解决方法
正是因为这条线:
return source->GetA(); 在这里,您尝试在您获得的指针上执行GetA函数.如果指向的对象是const,则该函数也必须是const,因为: > const和非const函数都可以在非const对象上执行 最好将所有不修改对象状态的函数标记为const,这样它们就可以用在const对象上(例如,在接受const T&作为参数的函数中). 所以在你的情况下,该类应该如下所示: class FooStruct { public: int GetA() const {return a;} }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |