gpt4 book ai didi

c++ - 重载返回类型?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:23:06 27 4
gpt4 key购买 nike

假设我有课

Class rofl {
int a;
float b;
rofl::rofl(int a, float b) {
this->a = a; this->b = b;
}
}

有没有可能做

rofl* sup = new rofl(5, 2.0f);
float hello = sup;

所以变量 hello 会得到 sup.b 的值?

最佳答案

是的,您可以重载类型转换运算符:

class Rofl {
public:
operator float() const { return b; }

...
};

参见 http://ideone.com/Y7UwV用于演示。

但是,请参阅 Scott Meyers 的第 5 项 More Effective C++ ,标题为“警惕用户定义的转换操作”。允许在复杂类型之间进行隐式转换通常会导致各种微妙的打字错误。

关于c++ - 重载返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11177418/

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