在 C++ OOPS 中访问对象中的元素

问题描述 投票:0回答:1

我正在学习 C++ 中的 OOPS。我尝试使用指针访问类数据成员。但它会引发错误。

#include <iostream>

using namespace std;

class A

{
    protected:
        int x;
    public:
        A()
        {
            x=10;
        }
};

class B:public A
{
   public:
   void out()
   {
       A *p=new A;
       cout<<p->x;
   }
};

int main()
{
   B b;
   b.out();
   return 0;
}

上面的代码给出的错误为

error: ‘int A::x’ is protected within this context
    |        cout<<p->x;

谁能解释为什么会出现错误?预期输出是打印 x 的值。预先感谢。

c++ class oop inheritance new-operator
1个回答
0
投票

这段代码中的问题与指针和创建类对象有关。在 B 类的 void out() 函数中,您使用动态内存分配(即 new A)来创建 A 类的对象,然后尝试访问该类的 protected 'x' 成员A. 由于 B 是继承类,因此它可以访问 x 成员。但是,由于您在类 B (new A) 中创建的对象属于类类型 A,因此无法在类外部访问受保护的成员。所以最终显示编译错误。 问题还在于 out() 函数创建了一个新的 A 对象,并从这个新对象而不是 B 对象打印 x 的值。

要解决此问题,您应该直接从类 B 的对象访问 x 成员,因为它是从类 A 派生的并且可以访问其受保护的成员。这是代码:

#include <iostream>

using namespace std;

class A
{
protected:
    int x;

public:
    A()
    {
        x = 10;
    }
};

class B : public A
{
public:
    void out()
    {
        // Access the 'x' member of the current 'B' object
        cout << x;
    }
};

int main()
{
    B b;
    b.out();
    return 0;
}

我希望这有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.