重载类实例变量
Overload Class Instance Variable
我一直在寻找这个,但没有任何运气。可能是我搜索了错误的单词,或者这是一个不寻常的请求(或者根本不可行)。
无论如何,我的问题:我希望能够使用类的实例......好吧,这里有一个非常简单的例子:
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" `<<`
}
要么允许att.value
通过public
,friend
船,要么编写一个函数。
另一种选择是构建一个铸造运算符来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;
}
相关文章:
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 为什么静态数组成员变量在调用对象的实例后不显示任何内容?
- 我有一个类,它创建了另一个类的实例.如何将变量通过第一个类传递到第二个类的实例化中?
- 返回 C++ 中的指针实例变量
- 是否可以将指向未实例化的对象的指针用作C++中的变量?
- "new"创建的实例的所有成员变量是否都存在于堆上而不是堆栈上?
- 类外的静态变量实例化
- XCode 警告"此处需要实例化变量'Singleton:<Foo>:_instance',但没有可用的定义
- 返回实例变量的c++方法可以访问变量中的数据,但不能更改它,但在编译时不会生成错误
- 变量模板,具有与实例一样多的参数
- 让类方法为每个实例保存不同的静态变量
- 使用动态布尔变量实例化模板
- “auto”每次创建一个新的变量实例
- 创建变量实例有什么不同?
- 类成员的C++静态成员变量实例化了两次
- 使用变量实例化模板化函数
- 全局静态变量实例化行为
- c++变量/实例初始化跨不同翻译单元的顺序
- 如何在win32下将全局变量实例化为c++中的第一件事?