有人可以向我解释以下编译器错误,该错误表明'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
包含两个x
变量。一个继承自每个父类。因此,要分配给A::x
还是B::x
都很不明确。仅仅因为一个不可访问并不意味着另一个将被自动选择。编译器无法知道您打算尝试分配给专用A::x
(这将是另一个错误)还是公用B::x
。
此外,如注释中所述,class C : public A,B
与class C : public A, public B
相同。在第一种情况下,您从A
公开继承,但从B
私有继承(因为class
的默认继承是私有继承,而struct
的默认继承是公开继承)。在第二种情况下,您将从两个基类公开继承。