gpt4 book ai didi

c++ - 返回带有成员变量的类对象

转载 作者:行者123 更新时间:2023-12-05 04:34:42 24 4
gpt4 key购买 nike

为什么即使我不返回基类,函数 test() 也能正常工作?编译会发生什么?谁能给我解释一下?

#include <iostream>

class Base {
public:
Base(){}
Base(int val): _val(val){};
~Base(){};

Base test(int n){
return (n);
}

int &operator *() { return (_val); };

private:
int _val;

};


int main()
{
Base base;
Base a;

a = base.test(42);
std::cout << *a << std::endl;

return (0);
}

最佳答案

您声明了一个接受int 的构造函数,并且您声明了test(int n) 应该总是返回一个Base 类。编译器知道为了创建一个 Base 对象,您不需要任何东西(默认构造函数)或 int,因此它使用带有 的构造函数创建一个对象>int 返回那个。

如果您愿意,您可以明确说明并执行类似以下操作并获得完全相同的行为:

Base test(int n){
return Base(n);
}

简而言之,n 被隐式转换为 Base 对象,因为您声明了一个只需要 int 的构造函数。

关于c++ - 返回带有成员变量的类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71166339/

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