gpt4 book ai didi

c++ - 重载类实例变量

转载 作者:行者123 更新时间:2023-11-30 00:47:09 25 4
gpt4 key购买 nike

我一直在寻找这个,但没有找到任何运气。可能是我在搜索错误的词,或者这是一个不寻常的请求(或者根本不可行)。

无论如何,我的问题是:我希望能够使用一个类的实例……好吧,这是一个非常简单的例子:

class attribute
{
float value;
float min;
float max;
}

attribute attr1;
attr1.value = 5.0f;

现在,基本上,我想像调用一样使用 attr1

attr1.value

所以当我说,

std::cout << attr1 << std::endl;

它会打印 5.0(或只是 5)。

谢谢!

最佳答案

你需要实现

std::ostream& operator<<(std::ostream& os, attribute const& att)
{
os << att.value;
return os; // this is how you "chain" `<<`
}

要么通过publicfriendship 允许att.value,要么编写一个函数。

另一种选择是构建一个转换运算符来float:

class attribute
{
public:
operator float() const
{
return value;
}

private:
/*the rest of your class here*/

但这可能会引入意想不到的歧义。

最后,如果您希望 attribute 表现得像数字类型,那么您可以根据需要重载更多运算符。例如,要重载 +=,您可以编写

template<typename Y>
attribute& operator+=(const Y& p)
{
value += p;
return *this;
}

关于c++ - 重载类实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35719714/

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