处理任务并完成几乎所有事情,除了我似乎无法列出类的操作符+功能.指导/指导将非常受欢迎,因为我似乎无法确定我做错了什么.
#include <iostream>
using namespace std;
class numDays {
private: // member variables
int hours;
double days;
public: // member functions
numDays(int h = 0) {
hours = h;
days = h / 8;
}
void setHours(int s) {
hours = s;
days = s / 8;
}
double getDays() {
return days;
}
numDays operator+(numDays& obj) {
// what to put here?
}
numDays operator- (numDays& obj) { // Overloaded subtraction
// and here?
}
numDays operator++ () { // Overloaded postfix increment
hours++;
days = hours / 8.0;
numDays temp_obj(hours);
return temp_obj;
}
numDays operator++ (int) { // Overloaded prefix increment
numDays temp_obj(hours);
hours++;
days = hours / 8.0;
return temp_obj;
}
numDays operator-- () { // Overloaded postfix decrement
hours--;
days = hours / 8.0;
numDays temp_obj(hours);
return temp_obj;
}
numDays operator-- (int) { // Overloaded prefix decrement
numDays temp_obj(hours);
hours--;
days = hours / 8.0;
return temp_obj;
}
};
int main() {
// insert code here...
numDays one(25), two(15), three, four;
// Display one and two.
cout << "One: " << one.getDays() << endl;
cout << "Two: " << two.getDays() << endl;
// Add one and two, assign result to three.
three = one + two;
// Display three.
cout << "Three: " << three.getDays() << endl;
// Postfix increment...
four = three++;
cout << "Four = Three++: " << four.getDays() << endl;
// Prefix increment...
four = ++three;
cout << "Four = ++Three: " << four.getDays() << endl;
// Postfix decrement...
four = three--;
cout << "Four = Three--: " << four.getDays() << endl;
// Prefix increment...
four = --three;
cout << "Four = --Three: " << four.getDays() << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您需要创建temp_obj并返回它,就像在postfix中一样operator++,但是您将更新成员temp_obj而不是更新任何内容this.
实际上,您可以将其设置为const成员函数,以便编译器检测您是否意外更新this.大多数人甚至使用非成员运算符重载operator+来使其成为对称关系.
不相关,但是:
days = h / 8; 是整数除法(余数被丢弃)days和hours并行,这是脆弱的.它似乎只hours应该是一个成员变量,而getDays函数(应该是const)可以动态计算它.operator++和operator--(没有伪参数的那些)不应该按值返回 - 这些函数应该更新成员this并返回对它的引用*this.专业提示:为避免代码重复,您可以像这样执行增量运算符(假设您希望它们都是成员函数):
numDays & operator++() // prefix
{
// your logic here, e.g. hours++;
return *this;
}
numDays operator++(int dummy) // postfix
{
return ++numDays(*this); // invokes prefix operator++ we already wrote
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
313 次 |
| 最近记录: |