以下两种访问私有(private)常量类成员的实现有什么区别?
// Auto& (compile ok)
class Foo {
private:
const int _foo;
public:
Foo(const int& in) : _foo(in) {}
auto& foo() { return _foo; }
}
// Explicit type (compiler error)
class Foo {
private:
const int _foo;
public:
Foo(const int& in) : _foo(in) {}
int& foo() { return _foo; }
}
使用 auto
编译器不会报错,但显式 int
类型声明实际上会给出编译器错误(这是由于常量)。在这种情况下,auto
推导了什么?
最佳答案
由于 _foo
是 const int
类型,auto
指的是 const int
。将您的“显式类型”代码更改为返回 const int&
,编译器应该不会再提示了。
关于c++ - const 类成员的自动扣除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36563757/