我有一个整数,我使用此处的模板解决方案将其封装为“属性”:
https://stackoverflow.com/a/4225302/3717478
template<typename T>
class Property
{
protected:
T& _value;
public:
Property(T& value) : _value(value)
{
} // eo ctor
Property<T>& operator = (const T& val)
{
_value = val;
return *this;
}; // eo operator =
operator const T&() const
{
return _value;
}; // eo operator ()
T& operator() ()
{
return _value;
}
T const& operator() () const
{
return _value;
}
};
但是,如果将属性标识符作为参数传递给需要可变数量参数的函数,例如 printf(),则传递的是类指针值而不是 int 值。
是否有我可以重载的运算符,以便传递 int 值?
最佳答案
您可以对类的对象使用 static_cast
运算符。
例如
int value = 10;
Property<int> p( value );
printf( "%d\n", static_cast<int>( p ) );
在本例中是转换运算符
operator const T&() const
{
return _value;
}; // eo operator ()
将被调用。
关于c++ - 当类作为参数传递给 printf() 时要重载什么运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34064593/