开发者

C++: Access to a public member function from outside of a class

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 hav开发者_如何学运维e 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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜