为什么x成员变量不明确?

问题描述 投票:4回答:1

有人可以向我解释以下编译器错误,该错误表明'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个回答
4
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.