C++ 类 : read value behave as different types

标签 c++ class operator-overloading assignment-operator

<分区>

我想创建一个类似这样的类:

class MyTime {
public:
    int seconds;
    int useconds;

    /*** functions ***/
}

但具有以下行为:

MyTime now;
double current_time = now; // returns double representing seconds

有没有一种方法可以做到这一点而不必定义 asDoubleSeconds() 函数?我可以通过某种方式重载赋值运算符来改变行为吗?

如果没有,有没有办法做这样的事情:

double current_time = double(now);

最佳答案

是的,实现 user-defined conversion operator :

class MyTime {
    // ...

    operator double() const;
};

MyTime::operator double() const {
    // compute and return a double
}

关于C++ 类 : read value behave as different types,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44762610/

相关文章:

php - 何时使用静态类与实例化类

c++ - 我正在尝试重载运算符<<

c# - 不使用点运算符访问类属性

C++从heredoc读取标准输入

c++ - 我应该删除 QDebug header 以进行发布吗?

c++ - 开始 Code::blocks 和 UnitTest++

c++ - 动态 C++ 函数参数

c# - 将 C# 对象保存到文件

python - 新手对类(class)的困惑

c++ - 重载 >> 使用 istream