【发布时间】:2016-11-29 18:07:40
【问题描述】:
在 C++11 中,可以使用 using 声明使私有基类的公共成员可供外部(公共)访问。例如
class A {
private:
int i = 2;
public:
void f() { i = 3; }
friend bool operator==(const A& l, const A& r) { return l.i == r.i; }
};
class B : private A {
public:
using A::f;
};
int main() {
B b, b2;
b.f();
}
b.f() 是可能的,因为B 的定义中的using A::f。
是否可以编写一个类似的声明,使友元函数operator==(A&, A&) 可以从B& 向上转换为A&,以便可以在main() 中调用b == b2?
【问题讨论】:
-
您希望一般情况下可以将
B向上转换为A?那为什么要使用私有继承呢?或者你只是想让operator==工作?那为什么不直接声明另一个operator==? -
需要注意的是友元函数不是类的成员,所以不应该使用“upcast”这个词。
标签: c++ c++11 c++14 using friend