c++类函数在另一个函数中不能按预期工作

c++ class function does not work as intended inside another function

本文关键字:不能按 工作 函数 类函数 另一个 c++      更新时间:2023-10-16

为了演示我的问题,让我们看看以下示例:

#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,还有一个类函数距离,它取一个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 &aconst(所以删除"const")可以消除错误。但为什么呢?这个网站的成员无数次告诉我要始终通过const引用,以防止复制对象。如果我不能通过const引用,这是否意味着我的函数WriteDistance在这个过程中以某种方式更改了a对象?有没有一些变通方法可以让它真正成为const

您的distance函数声称要修改它所调用的对象,这就是为什么您不能在类型为const MyClass的值上使用它。

你应该申报为

long double distance(const MyClass &b) const {
//                                     ^^^^^

第二个const意味着它不会修改类成员(即*this是函数中的const)。

用限定符const 声明成员函数

long double distance(const MyClass &b) const {
//...

如果您想用两个参数声明函数,那么将其设为静态。例如

static long double distance(const MyClass &a, const MyClass &b) {
//...

您需要为const对象的用法添加const限定版本函数。我们通常提供两个版本的函数声明,const和non-const。const版本用于const Class对象,就像您的const MyClass&b

void WriteDistance(const MyClass &a, const MyClass &b) const {
cout << a.distance(b) << endl;
}