在类成员中调用函数 (C++)
Zh
struct Z {
Z();
~Z();
void DoSomethingNasty();
}
Xh
struct X {
X();
~X();
void FunctionThatCallsNastyFunctions();
}
MainClass.h
#include "Z.h"
#include "X.h"
struct MainClass {
MainClass();
~MainClass();
private:
Z _z;
X _x;
}
X.cpp
X::FunctionThatCallsNastyFunctions() {
//How can I do this? The compiler gives me error.
_z.DoSomethingNasty();
}
我应该怎么做才能从 _z
对象调用 DoSomethingNasty()
函数?
Z.h
struct Z {
Z();
~Z();
void DoSomethingNasty();
}
X.h
struct X {
X();
~X();
void FunctionThatCallsNastyFunctions();
}
MainClass.h
#include "Z.h"
#include "X.h"
struct MainClass {
MainClass();
~MainClass();
private:
Z _z;
X _x;
}
X.cpp
X::FunctionThatCallsNastyFunctions() {
//How can I do this? The compiler gives me error.
_z.DoSomethingNasty();
}
What should i do in order to call DoSomethingNasty()
function from _z
object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编译器给出错误,因为
X
类中不存在_z
;它存在于MainClass
类中。如果您想从X
调用Z
对象的方法,则需要为X
提供其自己的Z
> 对象,否则您必须将一个对象作为参数传递给它。其中哪一个合适取决于您想要做什么。我认为您的困惑可能是这样的:您认为因为
MainClass
同时具有X
成员和Z
成员,因此它们应该能够访问彼此。事情不是这样的。MainClass
可以访问它们,但是_x
和_z
对象在它们的成员函数中,不知道它们自己的类之外的任何内容。The compiler is giving you an error because
_z
doesn't exist within theX
class; it exists within theMainClass
class. If you want to call a method on aZ
object fromX
, you either need to giveX
its ownZ
object or you have to pass one to it as a parameter. Which of these is appropriate depends on what you're trying to do.I think your confusion may be this: You think that because
MainClass
has both aX
member and aZ
member, they should be able to access each other. That's not how it works.MainClass
can access both of them, but the_x
and_z
objects, within their member functions, have no idea about anything outside their own class.您没有提供编译器错误,但从示例中我猜测编译器错误是因为您只声明了 DoSomethingNasty 函数但没有定义它。这会导致链接时出错。
尝试将以下代码添加到您的 .cpp 文件中
此外,正如 @Tyler 指出的那样,X 类没有名为
_z
的成员变量来调用该函数。You didn't provide the compiler error but from the sample I'm guessing the compiler error is because you only declared the DoSomethingNasty function but did not define it. This would result in an error at link time.
Try adding the following code to your .cpp file
Additionally as @Tyler pointed out, the X class does not have a member variable named
_z
from which to call the function on.