c++类-如何从另一个成员函数引用一个成员函数
C++ classes - how to reference a member function from another member function
我对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),一切都应该如你所愿。
相关文章:
- 如何使用指针传递给函数的数组中对象的函数成员
- c++构造函数成员初始化:传递参数
- 创建 std::函数,它返回具有函数成员值的变量.分段错误
- 如何在C++通过公共函数访问私有函数成员?
- 解释了构造函数成员初始化列表
- 调用std::函数成员时内存损坏
- 是否可以为模板类的模板函数成员设置别名?
- 捕获 lambda 函数C++成员变量
- 构造函数成员初始值设定项跨成员列出,安全吗?
- 获取与在模板参数中传递的函数成员类型相同的类
- 如何从公共函数成员访问地图私有成员
- C 构造函数成员分配优化
- 使用命名空间进行函数成员定义
- 函数成员作为 CUDA 内核的参数
- 模板基类函数成员的别名
- 函数成员中用于void和继承的enable_if
- 头文件中是否定义了一个很长的Class函数成员
- 类内/构造函数成员初始化
- 使用指向部分专用函数成员的指针自动填充向量
- 指向函数成员的指针