zwh*_*nst 14 c++ inheritance private base ambiguity
今天我对这段代码片段的名称引用不明确这一事实感到震惊:
class A
{
private:
typedef int Type;
};
class B
{
public:
typedef int Type;
};
class D : A, B
{
Type value;//error: reference to 'Type' is ambiguous
};
Run Code Online (Sandbox Code Playgroud)
唔!假设您是 class 的作者,A并且您的 class 已经被不同的人和不同的项目随处使用。有一天你决定重写你的A类。这是否意味着您不能在不破坏他人代码的情况下在新类中使用任何新的(甚至私有的)名称?
这里的约定是什么?
正如 @Jarod42 提到的,它需要遵循pimpl 惯用语(指向实现的指针)来分离接口和实现:
啊
#include <memory>
class A
{
public:
A();
~A();
private:
class AImpl;
std::unique_ptr<AImpl> pimpl;
};
Run Code Online (Sandbox Code Playgroud)
a.cpp
#include "A.h"
class A::AImpl
{
private:
typedef int Type;
/* .. */
};
A::A(): pimpl(new AImpl)
{
}
A::~A() = default;
Run Code Online (Sandbox Code Playgroud)
主程序
#include "A.h"
class B
{
public:
typedef int Type;
};
class D : A, B
{
Type value;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
242 次 |
| 最近记录: |