c++ - 没有从“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 &' 的已知转换
我怎样才能解决这个问题?
解决方案
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
,所以它的属性是一一设置的。
推荐阅读
- powerbi - Power BI:在表中格式化“度量”十进制数
- scala - 在 SKUBER 中定义自定义资源
- c++ - 税收计算程序将 0.00 返回到文件的 C++ 输出流
- java - 登录时从数据库中填充 JTable
- pyspark - pyspark Window 功能范围正在倒退?
- java - 我正在尝试查找字符串中元音的数量,但每次运行它都会返回 0。它有什么问题?
- android - 如何在 NativeScript 中正确显示 Android 启动画面?
- html - 我怎样才能在导航栏中有居中的链接和其他右/左定位的链接?
- java - 将两个 FragmentManager 类型导入同一个类
- java - 就 java 而言,“令牌”到底是什么?