c++ - 当类作为参数传递给 printf() 时要重载什么运算符

标签 c++

我有一个整数,我使用此处的模板解决方案将其封装为“属性”:

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/

相关文章:

c++ - 检测超出函数范围的未使用变量

c++ - 我如何使用方法来处理大量指针?

c++ - 在带有 std::greater 附加参数的 std::map 上使用三元运算符

c++ - C++ 中结构函数头中的声明(简单)

java - 是否存在 Java 到 C++ 转换器/工具?

c++ - 如何使用模板类作为模板参数?

c++ - 我应该为QWidget的派生定义析构函数吗

c++ - 如何将 sqlite3 + 扩展函数静态链接到 C/C++ 应用程序中?

c++ - CUDA 将 GpuMat 的 c 数组传递给内核

c++ - GTK+上的中小型开源项目示例