mmo*_*cny 15 c++ compiler-errors
我正在尝试使用两个具有相同名称的方法创建一个类,用于访问私有成员.一种方法是public和const限定,另一种方法是private和non-const(由朋友类用于通过引用返回来修改成员).
不幸的是,我收到编译错误(使用g ++ 4.3):当使用非const对象来调用方法时,g ++抱怨我的方法的非const版本是私有的,即使存在公共(const)版本.
这看起来很奇怪,因为如果私有非const版本不存在,一切都编译得很好.
有没有办法让这项工作?它是否在其他编译器上编译?
谢谢.
例:
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() */
}
Run Code Online (Sandbox Code Playgroud)
CB *_*ley 14
在访问检查之前发生重载解析,因此当您在非const A上调用a方法时,选择非const成员作为更好的匹配.然后编译器由于访问检查而失败.
没有办法"做这个工作",我的建议是重命名私有函数.是否需要私人访问器?
const如果对象被声明为,它只会选择版本const,否则它将选择非const版本(即使这会导致错误)。
这应该有效:
cout << ((const A*)&a1)->a() << endl;
Run Code Online (Sandbox Code Playgroud)
或这个:
A const& ra1 = a1;
cout << ra1.a() << endl;
Run Code Online (Sandbox Code Playgroud)