Calling Member Functions within Main C++

吃可爱长大的小学妹 提交于 2021-02-06 02:58:09

问题


#include <iostream>

using namespace std;

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

void MyClass::printInformation()
{
     return;
}

int main()
{

    MyClass::printInformation();

    fgetc( stdin );
    return(0);
}

How would I call the printInformation function within main? The error tells me that I need to use a class object to do so.


回答1:


Declare an instance of MyClass, and then call the member function on that instance:

MyClass m;

m.printInformation();



回答2:


If you want to make your code work as above, the function printInformation() needs to be declared and implemented as a static function.

If, on the other hand, it is supposed to print information about a specific object, you need to create the object first.




回答3:


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. :-)




回答4:


You need to create an object since printInformation() is non-static. Try:

int main() {

MyClass o;
o.printInformation();

fgetc( stdin );
return(0);

}



回答5:


declare it "static" like this:

static void MyClass::printInformation() { return; }



回答6:


you have to create a instance of the class for calling the method..




回答7:


On an informal note, you can also call non-static member functions on temporaries:

MyClass().printInformation();

(on another informal note, the end of the lifetime of the temporary variable (variable is important, because you can also call non-const member functions) comes at the end of the full expression (";"))



来源:https://stackoverflow.com/questions/682721/calling-member-functions-within-main-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!