【发布时间】:2010-11-15 03:16:52
【问题描述】:
我正在尝试创建一个具有两个同名方法的类,用于访问私有成员。一种方法是公共的和 const 限定的,另一种是私有的和非常量的(由朋友类使用,通过引用返回的方式修改成员)。
不幸的是,我收到编译错误(使用 g++ 4.3):当使用非常量对象调用该方法时,g++ 抱怨我的方法的非常量版本是私有的,即使是公共(常量)版本存在。
这看起来很奇怪,因为如果私有非常量版本不存在,一切都可以正常编译。
有什么办法可以使这个工作吗? 它可以在其他编译器上编译吗?
谢谢。
例子:
class A
{
public:
A( int a = 0 ) : a_(a) {}
public:
int a() const { return a_; }
private:
int & a() { return a_; } /* Comment this out, everything works fine */
friend class B;
private:
int a_;
};
int main()
{
A a1;
A const a2;
cout << a1.a() << endl; /* not fine: tries to use the non-const (private) version of a() and fails */
cout << a2.a() << endl; /* fine: uses the const version of a() */
}
【问题讨论】:
-
为什么会失败? C++ 允许从非 const 转换为 const,相对于函数参数。
标签: c++ compiler-errors