c++ - 虚拟继承和签名重叠

标签 c++

假设我们有以下代码:

struct A{
    virtual ~A(){}

    void f(){
        p = 42;
    }

    int p;
};

struct B : public virtual A{};
struct C : public virtual A{};
struct D : public B, public C, public A{}; //let's add non-virtual inheritance

int main(){
    D* pA = new D();
    pA->A::f(); //!

    return 0;
}

有什么办法可以在最基类A中将p设置为42吗? 以下构造 pA->A::f();将非虚拟继承的类 A 的 p 设置为 42。我们可以在不强制转换的情况下做到这一点吗?

最佳答案

首先,没有转换:您只需限定您想要的 A 版本,因为有多个版本。当然,您选择的符号实际上不起作用,因为它首先没有解决歧义。我猜你是想用类似的东西

pA->B::f();

如果您不想让类的用户承担选择调用哪个成员函数的负担,则必须为 D 提供合适的转发函数,例如:

void D::f() { this->B::f(); }

关于c++ - 虚拟继承和签名重叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9759023/

相关文章:

python - 使用cython从C++构造函数传播异常

c++ - 链接器错误,在 ubuntu 15.04 上使用 OpenCV 和 Eclipse CDT

c++ - 为什么 −π < atan2(y, x) ≤ π 而对于直线我们真的只需要从 0 到 π?

c++ - 运算符>> 在带有 std::ignore 的绑定(bind)元组上

C++赋值运算符重载

c++ - "terminated by a zero"是什么意思?

C++ WINAPI 通过 GetProcAddress 调用导出函数

c++ - 部分排序的快速排序

c++ - 使用多种颜色为 macOS 中的标题栏着色

c++ - Jetson TK1 - 嵌入式 Linux - 如何定期中断