C++ - Calling a function inside a class with the same name as the class
Solution 1
::A("Hello, world.");
should work fine. Basically it is saying "use the A
found in the global namespace"
Solution 2
Use the scope resolution operator ::
to access the name from the global scope:
void A::C() {
::A("Hello, world.");
}
Solution 3
I suggest you use namespaces. Put your class in a different namespace than the function.
namespace my_namespace1
{
void A() {}
}
namespace my_namespace2
{
struct A {};
}
int main()
{
my_namespace1::A();
my_namespace2::A my_a;
}
Of course, the real question is, why do you have a class and a function with a different name? A good easy rule is to make classes named WithABeginningCapitalLetter and functions withoutOne. Then you will never have this problem. Of course, the STL doesn't do this...
Xymostech
I know JavaScript pretty well Working at Cricket Health, co-developer of KaTeX and Aphrodite
Updated on July 10, 2022Comments
-
Xymostech almost 2 years
I was trying to write up a class in c++, and I came across a rather odd problem: calling outside functions inside of a class that have the same name as the class. It's kinda confusing, so here's an example:
void A(char* D) { printf(D); } class A { public: A(int B); void C(); }; A::A(int B) { // something here } void A::C() { A("Hello, World."); }
The compiler complains at the second to last line that it can't find a function A(char*), because it is inside the class, and the constructor has the same name as the function. I could write another function outside, like:
ousideA(char* D) { A(D); }
And then call outsideA inside of A::C, but this seems like a silly solution to the problem. Anyone know of a more proper way to solve this?