是否可以在没有常量的情况下将类对象引用设置为c++中的默认参数

Is it possible to set a class object reference as a default parameter in c++ without const?

本文关键字:设置 对象引用 c++ 参数 默认 情况下 是否 常量      更新时间:2023-10-16

例如:

Class Point{
  double x, y;
public:
     Point();
     bool testequal(const Point& p1, Point& p2 = Point()) const;
}

不起作用。它给了我一个错误:

error: could not convert 'Point()' from Point to Point&

如果我把它用作,这就行了

bool testequal(const Point& p1, const Point& p2 = Point()) const;

bool testequal(const Point& p1, Point p2 = Point()) const;

但我希望使用对象p2作为参考值,其数据可以在实现中更改。

编辑:

这是完整的程序。是的,这很琐碎——我更希望你不要评估对这段代码的需求,而是评论它是否可以实现。

如果没有,请说明原因,并告诉我正确的方法是什么。超载是唯一的选择吗?

#ifndef __POINT_H__
#define __POINT_H__
Class Point{
  double x, y;
public:
     Point();
     Point(double xx, double yy);
     bool testequal(const Point& p1, Point& p2 = Point()) const;
// this declaration fails. alternative is to use const Point& p2 or Point p2. 
// but it is vital that the default parameter should store some value in 
// it which can be accessed at the function call location without returning it.
}

#include "Point.h"
Point::Point(): x(0), y(0) {}
Point::Point(double xx, double yy): x(xx), y(yy) {}
bool Point::testequal(const Point& p1, Point& p2){
    if (this->x == p1.x && this->y == p1.y){
        p2.x = this->x;
        p2.y = this->y;
        return true;
    }
    else
        return false;
}

您可以添加一个重载:

bool testequal(const Point& p1, Point& p2) const;
bool testequal(const Point& p1) const
{
    Point dummy;
    return testequal(p1, dummy);
}