在类成员中调用函数 (C++)

发布于 2024-09-15 09:28:56 字数 617 浏览 9 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月下凄凉 2024-09-22 09:28:58

编译器给出错误,因为 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 the X class; it exists within the MainClass class. If you want to call a method on a Z object from X, you either need to give X its own Z 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 a X member and a Z 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.

他夏了夏天 2024-09-22 09:28:58

您没有提供编译器错误,但从示例中我猜测编译器错误是因为您只声明了 DoSomethingNasty 函数但没有定义它。这会导致链接时出错。

尝试将以下代码添加到您的 .cpp 文件中

void Z::DoSomethingNasty() {
  // Code here
}

此外,正如 @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

void Z::DoSomethingNasty() {
  // Code here
}

Additionally as @Tyler pointed out, the X class does not have a member variable named _z from which to call the function on.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文