Reputation: 19
I have a very simple and yet complicated (atleast for me) question on how to call a method/function outside a class but on a same namespace in c++/cli.
I know that you need to create an instance of an object before you can call a method which is inside a class, something like:
namespace Cars {
public ref class MyClass
{
void Honda(int i)
{
//some code
}
}
void Register()
{
MyClass c;
c.Honda(1);
//some code
}
}
But how do I do the opposite? Like how do I call Register()
inside the MyClass::Honda
function if they are on the same namespace but not on the same class?
I tried Cars::Register()
but it gives an error saying that:
Register() is not a member of "Cars".
Edit: I added the actual code that I tried to access the Register()
method.
namespace Cars {
public ref class MyClass
{
void Honda(int i)
{
Cars::Register();
}
}
void Register()
{
//some code
}
}
The line Cars::Register()
; do not give any error when I save but when I try to rebuild my application it gives the error below:
Error C2039 'Register': is not a member of 'Cars'
Error C3861 'Register': identifier not found
Just to note that when I put Register()
inside the MyClass
, everything works well (for some reason I just need to put it outside the class)
Thanks!
Upvotes: -1
Views: 220
Reputation: 29009
The problem:
The main problem is that Register()
should be defined (or at least declared) before calling it.
Another minor issue is that you are missing ;
at the end of the definition for ref class MyClass
.
Fixed version:
namespace Cars
{
// Defintion:
void Register()
{
//some code
}
public ref class MyClass
{
void Honda(int i)
{
Cars::Register();
}
};
}
Or alternatively:
namespace Cars
{
// Declaration:
void Register();
public ref class MyClass
{
void Honda(int i)
{
Cars::Register();
}
};
// Definition:
void Register()
{
//some code
}
}
Note: since you call Register
within the same namespace, you can actually drop the Cars::
qualifier, i.e. simply call: Register();
. You also keep it of course, if you think it improves readability.
Upvotes: -2