简体   繁体   中英

c++ calling method from outside of a class

Ok, I reduced my problem to something that looks really silly but I simply cannot understand why this:

#include <iostream>
class ABC{
public:
    void Print() { std::cout<<"ABC_TEST!\n"; }
};

int main(){
    Print();
    return 0;
}

Gives me: error: identifier "Print" is undefined Thanks in advance!

It should be like this :

#include <iostream>
class ABC{
public:
    void Print() { std::cout<<"ABC_TEST!\n"; }
};

int main(){
    ABC abc;
    abc.Print();
    return 0;
}

You need to create an object of type ABC before you can call instance methods(or member functions which are not static)

Alternatively, Print() can be a static function and you will be able to call it with the :: operator.

class ABC {
   public:
     static void Print() { std::cout << "ABC_TEST\n"; }
};

int main()
{
   ABC::Print();
   return 0;
}

Above all else, Print() can also be a global function:

void Print()
{
   std::cout << "ABC_TEST\n" ;
}

int main()
{
   Print();
   return 0;
}

Print() is a member function of ABC , so you can only call it on an instance of ABC :

ABC abc;
abc.Print();

As a completely unrelated note, in C++ a return with value 0 is implied, so it is not necessary to write return 0 .

Print() is a member function of your ABC class, you need an object to invoke it on:

int main()
{
    ABC abc; // This creates an instance of ABC

    abc.Print();
//  ^^^^
//  This invokes member function `Print()` on the object abc.

    return 0;
}

The address of abc will be passed as an implicit first parameter to function Print() : that parameter will be accessible inside of Print() (more generally, inside an invoked member function) as the this pointer.

If you try calling Print() as if it were a non-member, free function, no implicit this pointer would be passed, and it makes sense that the compiler complains about it.

If you want to be able to invoke Print() the way you did, you should make it a non-member function:

void Print() { std::cout<<"ABC_TEST!\n"; }

int main()
{
    Print(); // This is fine now!
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM