是否可以在没有常量的情况下将类对象引用设置为c++中的默认参数
Is it possible to set a class object reference as a default parameter in c++ without const?
例如:
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);
}
相关文章:
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 我们可以有一个 setter 成员函数作为从 const 对象引用的 const 吗?
- C++对象引用返回不同的值
- 对象引用中的字段以不同的方法返回不同的值
- 通过向构造函数其他对象引用页面来创建对象
- 使用 sscanf 设置结构引用的值
- QT:即使在static_cast后也无法在主窗口中设置对象的位置
- 将对象传递给 Java C++与使用 JNI 逐个设置对象参数
- V8 无法使用名称设置对象模板"console"
- 为什么在对象引用恒定时允许更改为另一个类的指针的成员变量
- 如何在C++中读取 HDF5 对象引用
- C++ 未定义的对象引用
- 从函数返回 libconfig 类设置对象引用
- qt vsaddin错误对象引用未设置为对象的istanse
- 当设置对象等于另一个函数的返回值时,为什么要调用移动构造函数/分配
- 在这种情况下,为什么使用 *此必需的对象引用返回对象引用
- 无法将成员变量设置为对象引用
- 对象引用未设置为对象的实例 (C++/CLI)
- 可视C++对象引用未设置为对象的实例
- 是否可以在没有常量的情况下将类对象引用设置为c++中的默认参数