简体   繁体   English

在C ++中具有类类型的函数是什么?

[英]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. 在这里,我将action类用作函数的类型。 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] ) (它不允许我返回this 。错误: [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. 在您的代码(和我的答案)中, move是正常功能。 Maybe you meant it to be a member function, in which case you could also return *this; 也许您是说它要成为成员函数,在这种情况下,您还可以return *this; to return the current object. 返回当前对象。

What is this called? 这个叫什么?

move is the name of a free function. move是自由函数的名称。 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. 完整的签名action move()告诉您,它的返回值是类型action一个实例,并且函数不需要任何参数。 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() . 在上述情况下,它是一个导致对action::action()的调用的声明。

what should I return in the function move? 我应该在函数移动中返回什么?

An instance of action , because the function signature says so: action的实例,因为函数签名是这样的:

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}; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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