从派生类对象访问重写的基类成员
我有两个类:
class A
{
public:
int i;
};
class B : public A
{
public:
int i;
};
假设我为类 B
创建了一个对象,
B b;
是否可以使用 b
访问 A::i
?
I have two classes:
class A
{
public:
int i;
};
class B : public A
{
public:
int i;
};
Suppose that I created an object for class B
B b;
Is it possible to access A::i
using b
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的!
bA::i
怎么样? <代码>;)Yes!
How about
b.A::i
?;)
是的:
Yes:
是的,你可以。要了解详情,请阅读此
从基类继承的成员的新实现。被重写声明重写的方法称为重写基方法。重写的基方法必须与重写方法具有相同的签名。
从具有重写方法的派生类中,您仍然可以使用 base 关键字访问具有相同名称的重写基方法。例如,如果您有一个虚拟方法 MyMethod(),并且在派生类上有一个重写方法,则可以使用以下调用从派生类访问该虚拟方法:
base.MyMethod()
Yes you can. To find out read this
An override method provides a new implementation of a member inherited from a base class. The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method.
From within the derived class that has an override method, you still can access the overridden base method that has the same name by using the base keyword. For example, if you have a virtual method MyMethod(), and an override method on a derived class, you can access the virtual method from the derived class by using the call:
base.MyMethod()
两种方式:
Two ways:
正如其他人回答的那样,这是可能的。
但在您发布的示例中,基本成员和派生成员是相同的,数据类型没有被覆盖。
这对于为基本成员定义新数据类型的派生类来说是相关的,如本文所示:C++ 继承。更改对象数据类型
It is possible, as others replied.
But in the example you posted, the base and derived members are the same, the data type was not overriden.
This would be relevant in the case of derived classes that define a new data type for the base members as shown in this post: C++ Inheritance. Changing Object data Types