Joh*_*ano 5 c++ inheritance multiple-inheritance
有人可以向我解释以下编译器错误,该错误表示“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;
}
Run Code Online (Sandbox Code Playgroud)
编辑:对于向我解释私有并不意味着它不能更改的人 - 我知道这一点,并在下面做了这个简单的例子,但这不是我要问的情况。
//
// 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;
}
Run Code Online (Sandbox Code Playgroud)
你的C
包含两个x
变量。从每个父类继承一个。因此,是否要分配给 theA::x
还是 the是不明确的B::x
。仅仅因为其中一个不可访问并不意味着另一个将被自动选择。编译器无法知道您是否打算尝试分配给 private A::x
(这将是一个不同的错误)或 public B::x
。
另外,正如评论中指出的,class C : public A,B
与不同class C : public A, public B
。在第一种情况下,您可以公开继承,A
但可以私有继承B
(因为私有继承是默认继承,与默认继承是公共继承class
不同)。struct
在第二种情况下,您将从两个基类公开继承。