【发布时间】: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++ Multiple parents with same variable name
-
在不相关的注释上,
class C : public A,B与class C : public A, public B不同。 -
好吧,关键是 A 类的 x 成员变量应该不能从 C 类访问。如果两个“x”变量具有相同的访问权限,这很明显会出错,但情况并非如此。
-
可变的副作用,是的,没错,这是我的遗漏咒语,想公开,公开继承,但仍然是一个错误,我会编辑它
标签: c++ inheritance multiple-inheritance