C++ 从C+中的方法返回对象+;
我相信这个问题的答案很简单,但我就是不能让它正常工作。我基本上创建了两个类;一个用于点,一个用于多边形。多边形由点的动态列表组成 但是,当我尝试重载points类中的+操作符并使其返回两个点的多边形时,我会得到som怪异的输出,并在关闭控制台窗口后出现“调试断言失败” 以下是+运算符重载方法:C++ 从C+中的方法返回对象+;,c++,C++,我相信这个问题的答案很简单,但我就是不能让它正常工作。我基本上创建了两个类;一个用于点,一个用于多边形。多边形由点的动态列表组成 但是,当我尝试重载points类中的+操作符并使其返回两个点的多边形时,我会得到som怪异的输出,并在关闭控制台窗口后出现“调试断言失败” 以下是+运算符重载方法: CPolygon CPoint::operator + (CPoint pointToAdd) { CPolygon polygon; polygon.addPoint(this);
CPolygon CPoint::operator + (CPoint pointToAdd) {
CPolygon polygon;
polygon.addPoint(this);
polygon.addPoint(pointToAdd);
cout << polygon.toString();
return polygon;
}
CPolygon CPoint::operator+(CPoint pointToAdd){
多边形;
多边形添加点(this);
多边形.addPoint(pointToAdd);
cout您的代码:
CPolygon CPoint::operator + (CPoint pointToAdd) {
CPolygon polygon;
polygon.addPoint(this);
polygon.addPoint(pointToAdd);
cout << polygon.toString();
return polygon;
}
CPolygon CPoint::operator+(CPoint pointToAdd){
多边形;
多边形添加点(this);
多边形.addPoint(pointToAdd);
cout您的多边形对象在堆栈上声明,在操作符作用域之后,您将失去对它的引用
尝试声明它:
CPolygon* polygon = new Polygon(...);
你的签名应该是这样的:
CPolygon* CPoint::operator + (CPoint pointToAdd)
实际上,使用原始指针是一个坏主意,您必须在范围之外处理它,更好的解决方案是使用智能指针:
std::auto_ptr<CPolygon> CPoint::operator + (CPoint pointToAdd)
{
std::auto_ptr<CPolygon> polygon(new CPolygon);
// do stuff here
return polygon;
}
std::auto_ptr CPoint::operator+(CPoint pointToAdd)
{
std::auto_ptr多边形(新的CPolygon);
//在这里做事
返回多边形;
}
//
{
std::auto_ptr<CPolygon> polygon = firstPoint + secondPoint;
// working with CPolygon
// auto_ptr frees polygon
}
{
std::auto_ptr polygon=firstPoint+secondPoint;
//与CPolygon合作
//自动释放多边形
}
我按照上面Plasmah和urzeit的建议做了,实现了多边形类的复制构造函数,猜猜看,它解决了问题!:)感谢所有帮助我的人
多边形类的复制构造函数如下所示:
CPolygon::CPolygon(const CPolygon & polygon) :
nrOfPoints(polygon.nrOfPoints)
{
points = new CPoint[nrOfPoints];
// Add all the points from the polygon to be copied
for(int i = 0; i < nrOfPoints; i++) {
points[i] = polygon.points[i];
}
}
CPolygon::CPolygon(常量CPolygon和多边形):
nrOfPoints(多边形。nrOfPoints)
{
点数=新的CPoint[nrOfPoints];
//添加要复制的多边形中的所有点
对于(int i=0;i
什么是o addPoint和CPolygon以及您在其中传递的值不应该是polygon.addPoint(*this);
?或者您是否同时拥有addPoint(const CPoint&)和addPoint(const CPoint*)
(或非const
版本)?由于我们对类型一无所知,一个疯狂的猜测是:你没有遵守3的规则你为你的多边形实现了一个复制构造函数吗?返回需要一个副本!Meh.Ugh.Eww.std::vector
。请看我编辑的文章。在那里你会看到我有两个addPoint方法,一个用于指针,一个用于值。1.返回原始pointers混淆了所有权,2.在原始代码中,局部变量不会被复制出来吗?“您将失去对它的引用”-按值返回不存在此问题。可能此链接将提供更多信息:@pavel.lazar:该链接太过时,无法考虑移动,这是您在这种情况下真正希望看到的,并且使用不正确的浅层默认复制构造函数可以得到。@pavel.lazar那篇文章几乎没有提到指针返回。它不会在引用返回的情况下,请注意一个悬空引用,这是最接近您所指的内容。对于值返回,它提到了返回值优化,这可以防止复制对象。总之,我想知道您是否真的阅读了整篇文章。您还应该实现移动构造函数,并使用该构造函数r您的局部变量返回,它将产生更好的性能,而且使用std::vector也可能会这样做,至少它会清理您的代码一点。
CPolygon::CPolygon(const CPolygon & polygon) :
nrOfPoints(polygon.nrOfPoints)
{
points = new CPoint[nrOfPoints];
// Add all the points from the polygon to be copied
for(int i = 0; i < nrOfPoints; i++) {
points[i] = polygon.points[i];
}
}