我有一个简单的类如下
class A {
protected:
int x;
};
class B : public A {
public:
int y;
void sety(int d) {
y = d;
}
int gety() {
return y;
}
};
int main() {
B obj;
obj.sety(10);
cout << obj.gety();
getch();
}
How can I set the value of the protected
instance variable A::x
from an instance of the derived class B
without creating an instance of class A
.
编辑:我们可以使用 B 的对象访问 A::x
的值吗?像 obj.x
?
原文由 Vijay 发布,翻译遵循 CC BY-SA 4.0 许可协议
B
是A
,因此创建B
的实例是创建 —c1bc848ad7d96138 的实例A
话虽这么说,我不确定你的实际问题是什么,所以这里有一些代码希望能澄清一些事情:obj
can accessA::x
just as an instance ofA
could, becauseobj
is implicitly an instance ofA
.