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

发布于 2024-12-17 23:03:22 字数 227 浏览 4 评论 0原文

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

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


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

How do I return a point object aggregated in a another class? I'm trying to return a point object that's a private member of the quad class. I have written the function and it compiles, but I don't know the correct syntax to call that function.

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


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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

み格子的夏天 2024-12-24 23:03:22

这将起作用:

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;

}

This will 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;

}
月棠 2024-12-24 23:03:22

return Point a; 是错误的。您可以创建一个对象然后返回,也可以在 return 语句本身中创建该对象。

正确的语法:

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


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

return Point a; is wrong. You either create a object and then return or have the object created in the return statement itself.

Correct syntax:

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


Point Quad::getA()
{
    return Point();
}
一枫情书 2024-12-24 23:03:22

在类内部

 Point* p;

GetA() 函数中。

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

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

对不起,我的错。心中有这个想法,但表达错误。

Inside class

 Point* p;

In GetA() function.

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

Returning a pointer would be a better solution. Maintaining a single pointer throughout the lifetime of the program would make it easier for the developer to properly destroy the same. For reference http://en.wikipedia.org/wiki/Singleton_pattern

Sorry my bad. Had this in the mind but conveyed it wrong.

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