gpt4 book ai didi

c++ - 什么是在 C++ 中调用的具有类类型的函数?

转载 作者:行者123 更新时间:2023-11-27 22:34:02 24 4
gpt4 key购买 nike

我一直在网上搜索,但没有找到关键字。假设我想使用类类型来创建方法/函数。这是一个简单的例子:

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

在这里,我使用 action 类作为函数的类型。这是我的问题:这叫什么?我如何使用类的构造函数?我应该在函数 move 中返回什么? (它不允许我返回 this。错误:[在非静态成员函数之外无效使用'this'])

最佳答案

What is this called?

move 是一个自由函数的名称。完整的签名 action move() 告诉您它的返回值是 action 类型的一个实例,并且这些函数不需要任何参数。请注意,自由函数不同于成员函数,因为它们与任何类都没有特殊关系。

How do I use the constructor of the class?

当您创建该类的实例时,将调用构造函数。示例:

action instance; // calls default constructor

请注意,您并不是真的直接调用构造函数。在上面的例子中,它是一个导致调用 action::action() 的声明。

what should I return in the function move?

action 的实例,因为函数签名是这样说的:

action move() { return action{}; }

如果你的构造函数接受参数,这里是一个调整后的例子:

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

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

关于c++ - 什么是在 C++ 中调用的具有类类型的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57143868/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com