繁体   English   中英

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类,并且有一个类函数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 &' 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在过程中以某种方式更改了对象? 是否有一些变通办法才能使其真正具有const

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

您应该将其声明为

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

第二个const表示它不会修改类成员(即*thisconst内的const )。

用限定符const声明成员函数

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

如果要用两个参数声明该函数,则使其为静态。 例如

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

您需要为const对象的用法添加const限定版本功能。 我们通常提供两个版本函数声明,即const和非const。 const版本用于const Class对象,例如const MyClass&b

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM