【问题标题】:Can t transform int type to time type(my class type)无法将 int 类型转换为时间类型(我的类类型)
【发布时间】:2019-06-22 11:15:45
【问题描述】:

我有一个应用程序可以处理时间数据(小时、分钟、秒)。

在类中添加下一个运算符: - (二元运算符)定义为成员函数:它返回两个操作数之间的差;如果operand1小于operand2,则返回时间0:0:0

只有打印函数和 toseconds() 函数起作用。

这是错误:

Error   2   error C2440: 'type cast' : cannot convert from 'const time' to 'long'       47  1   timeex2

#include <iostream>

using namespace std;

class time { 
    int hour, min, sec;

    void normalize(); // it transforms the sec and min values on the inside of
                      // [0,59] interval and hour values on the inside of
                      // [0, 23] interval.
                      // Ex: the time 25: 79: 80 is transformed in 2 : 20: 20

public:
    time(int=0, int=0, int=0); // values of the members are normalized

    void print1(); // print on the screen the values as hour : min : sec
    void print2(); // print on the screen the values as hour : min : sec a.m. / p.m.

    void operator-(const time&);

    void toseconds() {
        sec=3600*hour+60*min+sec;
        cout << sec;
    }

//  friend time operator+(const time t) {
//      time t1, t2, t3;
//      t3 = t1 + t2;
//      time::normalize();
//      return t3;
//  }

//  friend time operator>(time t1, time t2) {
//      toseconds(t1);
//      toseconds(t2);
//      if (t1 > t2)
//          cout << "\nt1 is bigger\n";
//      else
//          cout << "\nt1 is smaller\n";
//  }

//  friend time operator==(time t1, time t2) {
//      toseconds(t1);
//      toseconds(t2);
//      if (t1 == t2)
//          cout << "\nEqual\n";
//      else
//          cout << "\nNot equal\n";
//  }
};

void time::operator-(const time& t) {
    long a = *this; // The error is here
    long b = (long)t; // The error is here  
    if (a < b)
        cout << "\n0:0:0\n";
    else
        cout << "\nThe difference is " << a-b << endl;
}

time::time(int a, int b, int c) {
    hour = a;
    min = b;
    sec = c;
    normalize();
}

void time::normalize() {
    int s = sec;
    int m = min;
    int h = hour;
    sec = s % 60;
    min = (m + s/60) % 60;
    hour = (h + m/60 + s/3600) % 24;
}

void time::print1() {
    normalize();
    cout << hour << ":" << min << ":" << sec << endl;
}

void time::print2() {
    normalize();
    if (hour >= 13)
        cout << hour%12 << ":" << min << ":" << sec << " p.m." << endl;
    else
        cout << hour << ":" << min << ":" << sec << " a.m." << endl;
}

int main() {
    time t1(12,45,30), t2(0,0,54620), t3;
    t1.print1();
    t2.print1();
    t1.print2();
    t2.print2();
    cout << "\nTime t1 to seconds\n";
    t1.toseconds();
    t1.operator-(t2);
    cin.get();
    return 0;
}

【问题讨论】:

  • #include &lt;iostream&gt; using namespace std; class time { 组合起来可能不是最好的主意。
  • 我认为问题出在运算符上,您正在将类转换为 long,但没有可用的转换。我猜你想打电话给 toSeconds() 或类似的东西。不管 toSeconds 也是错误的。您正在覆盖秒数而不将其他 2 个值设置为 0。该函数很可能应该在不改变对象状态的情况下计算并返回秒数。还是我误解了你想做什么?
  • 操作员通常应该返回一个结果——而不是输出 anything 到控制台。
  • @CuriouslyRecurringThoughts 你猜对了,我只想在函数toseconds()中转换成秒,不用修改
  • '我只想在函数toseconds()中转换为秒,不修改'——那么你应该声明函数const。当然,你需要一个返回值......

标签: c++ class operator-overloading friend-function


【解决方案1】:

*this 是一个时间对象,下一节中也是'`':

void time::operator-(const time& t) {
    long a = *this; // convert *this to long
    long b = (long) t; // convert t to long

    if (a < b)
        cout << "\n0:0:0\n";
    else
        cout << "\nThe difference is " << a - b << endl;
}

您不能将time 变量类型转换为“long”变量类型,除非您实现“operator()”进行长转换。如果您不想重载类型“long”的强制转换运算符,您可以使用一个函数为您转换它(如您的 toseconds 函数,但它必须返回值,而不仅仅是打印它)。

没有强制转换操作符:

class time {
private:
    // ...

public:
    // ...
    long to_seconds() const { // the const is necessary so you will be able to use this method ovet the t parameter in the operator- function (because t defined as `const time&`)
        auto  local_sec = 3600 * hour + 60 * min + sec;
        // cout sec; // print the value
        return local_sec; // return the value
    }
    // ...
}

void time::operator-(const time& t) {
    long a = this->to_seconds(); // take the long value from *this object
    long b = t.to_seconds(); // take the long value from t object

    if (a < b)
        cout << "\n0:0:0\n";
    else
        cout << "\nThe difference is " << a - b << " seconds" << endl;
}

operator() 重载后它看起来像这样:

class time {
private:
    // ...

public:
    // ...
    operator long() const; // Declare operator overloading for `long` type
    long to_seconds() const { // the const is necessary so you will be able to use this method ovet the t parameter in the operator- function (because t defined as `const time&`)
        auto local_sec = 3600 * hour + 60 * min + sec;
        // cout sec; // print the value
        return local_sec; // return the value
    }
    // ...
}

time::operator long() const {
    return to_seconds(); // return the desired long value in cast procedure
}

void time::operator-(const time& t) {
    long a = *this; // cast *this object from `time` type into `long` type
    long b = t; // cast t object from `time` type into `long` type

    if (a < b)
        cout << "\n0:0:0\n";
    else
        cout << "\nThe difference is " << a - b << " seconds" << endl;
}

【讨论】:

    【解决方案2】:

    通常,操作符应该返回一个结果:

    time time::operator-(const time& t);
    

    然后在您的运营商内部,您转换为long

    long a=*this;
    long b=(long)t;
    

    唯一:没有任何这样的演员表操作员!

    这种类型转换仅存在于从一种基本数据类型(intunsigned longchardouble,...)到另一种。如果涉及任何其他数据类型,则必须显式定义强制转换运算符。

    所以: 上课时间 { 上市: 显式运算符 long() { 返回 3600L小时 + 60Lmin + 秒; // ^ ^ // 使用长文字确保小时和分钟将被转换 // 在乘法之前也一样长 - 然后和其他加数一样 // 已经很长了,sec 也将被转换为。 } };

    有了它,你现在可以转换为 void。顺便说一句:explicit 关键字确保您需要显式转换,否则,它将在适当的上下文中隐式应用:

    time t;
    long l0 = t;                    // possible only without keyword
    long l1 = static_cast<long>(t); // required with (alternatively C-style cast)
    

    不过,现在您将构造一个新的时间对象以作为结果返回:

    a -= b;
    return a < 0 ? time(0, 0, 0) : time(a / 3600, a / 60 % 60, a % 60);
    

    操作员不应该输出任何东西,相反,您应该对返回的结果执行此操作。

    但是,一个问题是,从结果 operator- 中,您无法区分两个时间值之前是否相等或第一个运算符小于。

    所以你需要比较之前

    time t1, t2;
    if(t1 < t2)
        std::cout << "\n0:0:0\n";
    else
        std::cout << "\nThe difference is " << static_cast<long>(t1 - t2) << std::endl;
    

    如您所见,任何输出都在 运算符之外完成...当然,这需要适当定义的 bool time::operator&lt;(time const&amp; other); 或独立变体 bool operator&lt;(time const&amp; x, time const&amp; y);(这是我个人更喜欢)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-20
      • 2020-11-18
      • 2015-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多