C++类 - 如何从另一个成员函数引用成员函数
我对 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
}
I'm very new to c++ classes, so this is probably a really obvious question, but because I'm not familiar with the lingo yet I cant seem to be able to get a correct search term.
Anyway, what I am trying to do is have a public function in a class access a private function in same class.
eg
//.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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
函数
useful
被声明为返回float
,但您将其定义为返回int
。对比
与
如果将声明更改为 int important(float, float) 并从函数中返回一些内容,它将正常工作。
The function
useful
is declared to return afloat
, but you define it as returning anint
.Contrast
vs
If you change the declaration to
int useful(float, float)
and return something from the function it will work fine.您的返回类型不匹配:
编译器会查找完全匹配的函数定义。您收到的编译器错误可能是在抱怨以下事实:a) 找不到
floatUsed()
,或者 b) 当您谈论 < 时不知道您的意思代码>int有用。确保这些匹配,并且在
bar
中调用useful
应该可以正常工作。Your return types don't match:
The compiler looks for a function definition that matches exactly. The compiler error that you are getting is probably complaining about the fact that it a) can't find
float useful()
, or b) doesn't know what you mean when you're talking aboutint useful
.Make sure those match, and calling
useful
withinbar
should work just fine.由于您还没有发布编译器给您的错误消息,所以我会猜测一下。 .h 和 .cpp 文件中
useful()
的返回类型不匹配。如果你让它们匹配(都是 int 或都是 float),一切都应该按你的预期工作。Since you haven't posted the error message your compiler gives you, I'll take a guess. The return types of
useful()
don't match in the .h and .cpp files. If you make them match (both int or both float) everything should work as you expect.