【问题标题】:Is not a nonstatic data member or base class of不是非静态数据成员或基类
【发布时间】:2013-11-12 07:25:20
【问题描述】:

我有以下类,我正在尝试使用 H 类的对象访问基成员,我收到 H::a is ambiguous 警告。

class E {
public:
    E() : a(11) { }
    int a;
};

class F : public E {
public:
    F() : b(22) { }
    int b;
};

class G : public E {
public:
    G() : c(33) { }
    int c;
};

class H: public F, public G {
public:
    H() : d(44) { }
    int d;
};

我尝试将数据成员设为静态,但它不允许我在基本构造函数中对其进行初始化。有什么办法可以解决这两个问题?

【问题讨论】:

  • 这是 C++ 吗?如果是,您应该添加 c++ 标签。
  • 是的,谢谢。我一直忘记这一点。
  • 模棱两可的。你有两个a,一个来自 E 的 F 派生,一个来自 E 的 G 派生。要么通过全分辨率选择一个,要么使用虚拟继承。

标签: c++ class


【解决方案1】:

类“H”有两个称为“a”的变量,一个从 F 派生,一个从 G 派生。您可以使用限定符,

H::a

或者您可以使用“虚拟”继承说明符(请参阅https://stackoverflow.com/a/419999/257645

#include <iostream>

struct A {
    int a;
};

struct B : virtual public A {
};

struct C : virtual public A {
};

struct D : virtual public B, virtual public C {
    void d1() { a = 1; }
    void d2() { a = 2; }
};

int main() {
    D d;
    d.d1();
    d.d2();
    std::cout << d.a << std::endl;
}

http://ideone.com/p3LPe0

【讨论】:

  • 在 OP 的代码中,它们不是函数;它们是变量的成员。
  • 是的,我打算同时演示两者,但我变得懒惰了 - 将它们更改为变量只是为了与他的帖子保持一致。
  • +1 前提是正确的。有关如何从集中基类的角度调用虚拟基类初始化的示例,see this link,并特别注意在构造时从 B 和 C 子类中看似 missing 构造函数的初始化程序调用D.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-14
  • 2016-04-30
  • 1970-01-01
  • 1970-01-01
  • 2013-08-31
  • 2013-05-03
  • 2012-04-13
相关资源
最近更新 更多