【问题标题】:Why is the x member variable ambiguous?为什么 x 成员变量不明确?
【发布时间】:2020-01-25 15:16:52
【问题描述】:

有人可以向我解释以下编译器错误,即“x”是一个模棱两可的引用吗?

如果编译器知道其中一个变量实际上是不可访问的,为什么它不能允许这样做?

class A {
    int x; // private here
};

class B {
public:
int x; // public here
};

class C : public A, public B {

};

int main() {

    C c;
    c.x = 5; // here is the error

    return 0;
}

编辑: 对于向我解释私有并不意味着不能更改的人 - 我知道这一点,并在下面做了这个简单的例子,但我问的不是这种情况。

//
// the goal is to hack x, y values
//
#include <stdio.h>
#include <memory>

class A {
    int x;
    int _r;
    double y;
public:
    A() { x = 1; y = 0.5; _r = 0; }
    void foo() { printf("x = %d, y = %lf, _r = %d\n", x, y, _r); }
};

int main() {

    struct _B {
        int x = 2;
        double y = 1.5;
    } b;

    A a;

    a.foo();    // gives "x = 1, y = 0.500000, _r = 0"
    memcpy(&a, &b, sizeof(_B)); // where the sizeof B is eq 16 (4 for int, 4 for padding, 8 for double)
    memcpy(&a, &b, sizeof(b.x) + sizeof(b.y)); // that is undefined behaviour, in this case _r is overridden
    a.foo();    // gives "x = 2, y = 1.500000, _r = -858993460" (_r is just a part of floating point y value but with invalid cast)

    return 0;
}

【问题讨论】:

标签: c++ inheritance multiple-inheritance


【解决方案1】:

您的 C 包含两个 x 变量。从每个父类继承一个。因此,您是否要分配给A::xB::x 是不明确的。仅仅因为一个不可访问并不意味着另一个将被自动选择。编译器无法知道您是打算尝试分配给私有A::x(这将是一个不同的错误)还是公共B::x

此外,如 cmets 中所述,class C : public A,Bclass C : public A, public B 相同。在第一种情况下,您从A 公开继承,但从B 私下继承(因为私有继承是class 的默认值,而struct 的默认值是公共继承)。在第二种情况下,您将从两个基类公开继承。

【讨论】:

  • 嗯,没错,我刚刚修复了它,因为双重公共继承是我想做的,只是想念我的咒语。但是,我只是好奇是否有来自 c++ 标准的反馈。在 clang、gcc 和 MS 编译器中对其进行了测试,并且都报告了相同的错误。如果编译器知道其中一个实际上无法访问,为什么他们不允许这样做?
  • @JohnySiemanoKolano 因为这就是 C++ 标准所说的应该是这样的。
  • 它们都可以访问:)
  • mfnx,在这种情况下 A::x 不可访问,被声明为私有。
  • @JohnySiemanoKolano private 不会使非法程序合法。
【解决方案2】:

编译器在编译时检查歧义。因为歧义检查发生在访问控制或类型检查之前,所以当它发现存在歧义时,编译器还不知道分配给这些变量的访问控制,因此会引发错误。希望能回答你的问题

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 2022-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多