从派生类对象访问重写的基类成员

发布于 2024-09-26 03:49:47 字数 232 浏览 6 评论 0原文

我有两个类:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

眼角的笑意。 2024-10-03 03:49:47

是否可以使用 b 访问 A::i?

是的!
bA::i 怎么样? <代码>;)

Is it possible to access A::i using b?

Yes!
How about b.A::i? ;)

谁的年少不轻狂 2024-10-03 03:49:47

是的:

int main()
{
    B b;

    b.i = 3;
    b.A::i = 5;

    A *pA = &b;
    B *pB = &b;
    std::cout << pA->i << std::endl;
    std::cout << pB->i << std::endl;
}

Yes:

int main()
{
    B b;

    b.i = 3;
    b.A::i = 5;

    A *pA = &b;
    B *pB = &b;
    std::cout << pA->i << std::endl;
    std::cout << pB->i << std::endl;
}
很快妥协 2024-10-03 03:49:47

是的,你可以。要了解详情,请阅读

从基类继承的成员的新实现。被重写声明重写的方法称为重写基方法。重写的基方法必须与重写方法具有相同的签名。

从具有重写方法的派生类中,您仍然可以使用 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()

失去的东西太少 2024-10-03 03:49:47

两种方式:

struct A{
    A():i(1){}
    int i;
};

struct B : A{
    B():i(0), A(){}
    int i;
};

int main(){
    B b;
    cout << b.A::i;
    cout << (static_cast<A&>(b)).i;
}

Two ways:

struct A{
    A():i(1){}
    int i;
};

struct B : A{
    B():i(0), A(){}
    int i;
};

int main(){
    B b;
    cout << b.A::i;
    cout << (static_cast<A&>(b)).i;
}
如果没有 2024-10-03 03:49:47

正如其他人回答的那样,这是可能的。
但在您发布的示例中,基本成员和派生成员是相同的,数据类型没有被覆盖。

这对于为基本成员定义新数据类型的派生类来说是相关的,如本文所示: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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文