c++类函数在另一个函数中不能按预期工作
c++ class function does not work as intended inside another function
为了演示我的问题,让我们看看以下示例:
#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 &a
const
(所以删除"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;
}
- C++从其他 constexpr 创建 lambda 不能按顺序执行 Constexpr
- 为什么 HeapFree() 不能正常工作?
- std::chrono::d uration 可以按秒初始化,但不能按毫秒初始化?
- 为什么"std::is_function_v"不能按预期工作?
- C++自定义删除运算符不能正常工作?
- 我怎么不能按课程代码的降序对数字进行排序
- 为什么使用 exec() 重新启动程序不能正常工作?
- C++:返回本地对象,但不能正常工作
- 为什么带lcov的codecov在Travis上不能正常工作,而在我当地的Linux Mint上却不能正常工作
- 为什么sizeof函数在这里不能正常工作
- 为什么将可执行文件重命名为临时文件的此代码段不能按预期工作?
- c++类函数在另一个函数中不能按预期工作
- 为什么这个简单的批处理方法不能按预期工作?
- 为什么 std::is_copy_constructible 不能按预期工作
- 为什么 std::codecvt<wchar_t、char、mbstate_t> 不能按定义工作?
- 为什么我的内联汇编程序不能按预期工作
- 这个模板"specialization"代码在做什么,为什么它可以编译但不能按预期工作?
- 为什么类型推导不能按预期工作
- 为什么"extern const int n;"不能按预期工作?
- 在c++中对整数数组进行线性搜索时,SSE比较不能按预期工作