为了演示我的问题,让我们看一下以下示例:
#include "stdafx.h"
#include <iostream>
using namespace std;
class MyClass {
public:
long double x, y;
MyClass(const long double &xx = 0, const long double &yy = 0);
long double distance(const MyClass &b) {
return sqrt((x - b.x)*(x - b.x) + (y - b.y)*(y - b.y));
}
};
MyClass::MyClass(const long double &xx, const long double &yy) {
x = xx; y = yy;
}
void WriteDistance(const MyClass &a, const MyClass &b) {
cout << a.distance(b) << endl;
}
int main()
{
MyClass a = MyClass(2., 3.);
MyClass b = MyClass(3., 4.);
cout << a.distance(b) << endl;
return 0;
}
有一个类,MyClass
并且有一个类函数 distance ,它接受一个MyClass
变量并返回现有点和参数点之间的距离。
问题是:在 main() 中,该函数有效(没有错误)。但是,WriteDistance() 函数中存在错误,内容为:the object has type qualifiers that are not compatible with the member function "MyClass::distance"
和'long double MyClass::distance(const MyClass &)': cannot convert 'this' pointer from 'const MyClass' to 'MyClass &'
。
如果我重载距离函数(不仅要获取一个 MyClass 对象,还可以获取两个长双精度值,只是为了方便使用),错误将显示为:no instance of overloaded function "MyClass::distance" matches the argument list and object (the object has type qualifiers that prevent a match)
和'MyClass::distance': 2 overloads have no legal conversion for 'this' pointer
。
问题是:为什么会发生此错误以及如何预防?我发现不制作MyClass &a
const
(所以删除“ const
”)可以消除错误。但为什么?该站点的成员无数次告诉我,始终通过const
引用传递以防止对象的复制。如果我不能通过const
引用传递,这是否意味着我的函数WriteDistance
在此过程中以某种方式更改了 a 对象?是否有一些解决方法能够真正拥有它const
?
您的distance
函数声称要修改调用它的对象,这就是您不能在 type 值上使用它的原因const MyClass
。
你应该把它声明为
long double distance(const MyClass &b) const {
// ^^^^^
该第二const
装置将不会修改类成员(即*this
是const
在函数内)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句