C++:从类外部访问公共成员函数

发布于 2024-10-04 23:55:52 字数 412 浏览 0 评论 0原文

我在单独的文件中定义了一个类,有时我需要从另一个源文件访问其中一个公共成员函数。由于某种原因,我忘记了如何做到这一点,编译器给了我一个错误。

我有 classA.h 与类 A 的定义类似:

class classA {
  public:
  int function1(int alpha);
}

和一个单独的文件 classA.cpp 与实现。然后在其他一些文件 blah.cpp 中,我包含标头并尝试像这样访问它:

 classA::function1(15);

我的编译器拒绝它,并出现错误,因为它找不到“classA::function1(int)”的匹配项。
如果重要的话,我使用 Embarcadero RAD studio 2010。

I have a class defined in a separate file and at some point I need to access one of the public member functions from another source file. For some reason, I forgot how to do that and compiler gives me an error.

I have classA.h with definition of class A similar to this:

class classA {
  public:
  int function1(int alpha);
}

And a separate file classA.cpp with the implementation. And then in some other file blah.cpp I include the header and try to access it like this:

 classA::function1(15);

and my compiler refuses it with error that it could not find a match for 'classA::function1(int)'.
I use Embarcadero RAD studio 2010 if that matters.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

黯淡〆 2024-10-11 23:55:52

要调用“正常”函数,您需要一个实例。

classA a;
a.function1(15);

如果您想使用 classA:: 调用该函数,那么它需要是static

classA {
  public:
    static int function1(int alpha);
};

//...
classA::function1(15);

请注意,在静态方法内部,您无法访问任何非静态成员变量,出于同样的原因 - 没有实例提供上下文。

To call a 'normal' function, you need an instance.

classA a;
a.function1(15);

If you want to call the function using classA:: then it needs to be static.

classA {
  public:
    static int function1(int alpha);
};

//...
classA::function1(15);

Note that inside a static method, you can't access any non-static member variables, for the same reason - there is no instance to provide context.

☆獨立☆ 2024-10-11 23:55:52

function1 是静态方法吗?如果不是,那么您需要该类的对象来调用成员函数。

在 blah.cpp 中包含 classA.h 并创建 A 类的对象,然后调用成员函数。

Is function1 a static method ? If no, then you need an object of that class to call a member function.

Include classA.h in your blah.cpp and create an object of Class A and then call the member function.

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