首页 > 解决方案 > 没有从“int”到“时间”的可行转换

问题描述

我在用户定义的+运算符中遇到错误:

#include <iostream>

using namespace std;

class Time{
    int h;
    int m;
    int s;

public:
    Time();    
    Time(int x,int y, int z) {
        h=x;
        m=y;
        s=z;
    } 

    operator int() {
        return(h*3600 + m*60 + s);    
    } 

    void display() { 
        cout<<h<<endl;
        cout<<m<<endl;
        cout<<s<<endl;
    }
};      

int main(){
    Time t1(2, 3, 4);
    Time t2 = 200 + (int)t1;

    t2.display();  
}

注意:候选构造函数(隐式复制构造函数)不可行:第一个参数没有从 'int' 到 'const Time &' 的已知转换

我怎样才能解决这个问题?

标签: c++operator-overloading

解决方案


operator+您可以通过更改您的来解决您的问题

Time operator+(int total){
    total=total+h*3600+m*60+s;
    Time temp;
    temp.h = total / 3600;
    temp.m = (total % 3600) / 60;
    temp.s = total % 60;

    return temp;
}

首先,按照您的示例计算总秒数。然后创建一个临时Time的。由于它不能从一个创建int,所以它的属性是一一设置的。


推荐阅读