简体   繁体   中英

What is a function with a class type called in C++?

I've been searching across the web but seen to not find the keyword. let's say I want to use the class type to create a method/function. Here is an easy example:

struct action{
//constructor
action(int n){
}
};
action move(){
}

here, I'm using the action class as the type of the function. Here are my questions: What is this called? How do I use the constructor of the class? what should I return in the function move? (it doesn't let me return this . error: [invalid use of 'this' outside of a non-static member function] )

There's no special name for this situation. It's perfectly common.

You call the constructor in all the usual ways, eg

action move() {
    return action(42);
}

or

action move() {
    action a(42);
    return a;
}

In your code (and my answer) move is a normal function. Maybe you meant it to be a member function, in which case you could also return *this; to return the current object.

What is this called?

move is the name of a free function. The full signature action move() tells you that its return value is an instance of type action and that the functions doesn't expect any parameters. Note that free functions are different from member functions in that they don't have a special relationship to any class.

How do I use the constructor of the class?

The constructor is called when you create an instance of that class. Example:

action instance; // calls default constructor

Note that you don't really invoke constructors directly. In the above case, it's a declaration that leads to a call to action::action() .

what should I return in the function move?

An instance of action , because the function signature says so:

action move() { return action{}; }

If your constructor takes parameters, here's an adjusted example:

struct action {
    action(int n) { /* do stuff with the argument... */ }
};

action move() { return action{42}; }

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