如何在 c++ 中输出指针对象的属性(具有 2 个或更多属性)

How do i output properties of a pointer object in c++ (with 2 or more properties)

本文关键字:属性 具有 c++ 输出 对象 指针      更新时间:2023-10-16
Class A
{ 
  public:
    A();
    A(int x , int y);
  Private:
    int x;
    int y;
}
Class B
{
   public:
   B();
   A getApointerobject() const;
   Private:
   A *APointerObject;
int main()
{ 
  B bObj;
    cout << bObj.getApointerobject(); //i overloaded the << so that i can //output B objects but it crushes  
}
//Class B implementation (This is where i struggle)
  A getApointerobject() const { 
   return *getApointerobject;
}

在 B::getApointerobject() 中,你递归地调用它。您应该更改为

A getApointerobject() const { 
    return *APointerObject;
}

在调用 getApointerobject() 方法之前是否初始化了 B::APointerObject?

getApointerobject中,您尝试返回方法getApointerobject本身的地址。我猜你的代码现在甚至没有编译?

我猜你想归还你的APointerObject

  A B::getApointerobject() const { 
   return *this->APointerObject;
}

但请注意:内置类型(包括简单指针)没有默认构造函数。因此,由于您没有在class B构造函数中初始化APointerObject,因此您将使用野生指针。这意味着您的程序会在运行时崩溃或更糟(未定义的行为)