c++类-如何从另一个成员函数引用一个成员函数

C++ classes - how to reference a member function from another member function

本文关键字:函数 成员 一个 引用 另一个 c++      更新时间:2023-10-16

我对c++类非常陌生,所以这可能是一个非常明显的问题,但是因为我不熟悉术语,我似乎无法得到一个正确的搜索词。

无论如何,我要做的是让一个类中的公共函数访问同一个类中的私有函数。

//.h file:
class foo {
float useful(float, float);
public:
int bar(float);
};
//.cpp file:
int foo::useful(float a, float b){
//does something and returns an int
}
int foo::bar(float a){
//how do I access the 'useful' function in foo?? eg something like
return useful(a, 0.8); //but this doesnt compile
}

函数useful被声明为返回一个float,但是您将它定义为返回一个int

float useful(float, float);

int foo::useful(float a, float b){
    //does something and returns an int
}

如果您将声明更改为int useful(float, float)并从函数返回一些东西,它将正常工作。

您的返回类型不匹配:

//.h file:
class foo {
float useful(float, float);      // <--- THIS ONE IS FLOAT ....
public:
int bar(float);
};
//.cpp file:
int foo::useful(float a, float b){       // <-- ...THIS ONE IS INT. WHICH ONE?
//does something and returns an int
}
int foo::bar(float a){
//how do I access the 'useful' function in foo?? eg something like
return useful(a, 0.8); //but this doesnt compile
}

编译器查找与之完全匹配的函数定义。编译器错误,你得到的可能是抱怨的事实,它a)找不到float useful(),或b)不知道你的意思,当你谈论int useful

确保这些匹配,并且在bar中调用useful应该工作得很好。

由于您还没有发布编译器给您的错误消息,我将猜测一下。useful()的返回类型在.h和.cpp文件中不匹配。如果你让它们匹配(都是int或float),一切都应该如你所愿。