如何返回聚合在另一个类中的点对象

How do I return a point object aggregated in a another class?

本文关键字:另一个 对象 何返回 返回      更新时间:2023-10-16

如何返回聚合在另一个类中的点对象?我试图返回一个点对象,它是quad类的私有成员。我已经写了这个函数,它可以编译,但是我不知道调用这个函数的正确语法。

Point Quad::getA()
{
    return Point a;
}

 void Quad::check()
 {
    cout << this->getA();  //will not work
 }

可以:

class Quad {
  Point a;
  Point getA();
  void check();
};
Point Quad::getA()
{
    return a;
    // or: return Point(); 
    // to return a new point
}
void Quad::check()
{
    cout << getA(); // requires << be overloaded
    // perhaps this is what you want:
    // cout << getA().x;
}

return Point a;错误。您可以创建一个对象然后返回,或者在返回语句中创建该对象。

正确的语法:

Point Quad::getA()
{
    Point a;
    return a;
}

Point Quad::getA()
{
    return Point();
}

内部class

 Point* p;

在GetA()函数中

if (p== null) {
   p= new Point();
 }
return p;

返回一个指针将是更好的解决方案。在程序的整个生命周期中保持单个指针将使开发人员更容易正确地销毁该指针。参考http://en.wikipedia.org/wiki/Singleton_pattern

对不起我的错。我有这个想法,但传达错了。

相关文章: