Calling Member Functions within Main C++

前端 未结 7 1509
野的像风
野的像风 2021-02-04 12:24
#include 

using namespace std;

class MyClass
{
public:
       void printInformation();
};

void MyClass::printInformation()
{
     return;
}

int main(         


        
7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-04 12:41

    From your question it is unclear if you want to be able use the class without an identity or if calling the method requires you to create an instance of the class. This depends on whether you want the printInformation member to write some general information or more specific about the object identity.

    Case 1: You want to use the class without creating an instance. The members of that class should be static, using this keyword you tell the compiler that you want to be able to call the method without having to create a new instance of the class.

    class MyClass
    {
    public:
        static void printInformation();
    };
    

    Case 2: You want the class to have an instance, you first need to create an object so that the class has an identity, once that is done you can use the object his methods.

    Myclass m;
    m.printInformation();
    
    // Or, in the case that you want to use pointers:
    Myclass * m = new Myclass();
    m->printInformation();
    

    If you don't know when to use pointers, read Pukku's summary in this Stack Overflow question.
    Please note that in the current case you would not need a pointer. :-)

提交回复
热议问题