gpt4 book ai didi

C++ - 重载 operator+ 接受一个参数

转载 作者:搜寻专家 更新时间:2023-10-31 00:12:55 24 4
gpt4 key购买 nike

正在做一项作业,几乎所有的事情都完成了,除了我似乎无法布置类(class)的 operator+ 功能。指导/方向将非常受欢迎,因为我似乎无法确定我做错了什么。

#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;
}

最佳答案

你需要创建一个 temp_obj 并返回它,就像你在后缀 operator++ 中所做的那样,但是你将更新 temp_obj 的成员而不是更新 this 中的任何内容。

事实上,您可以将其设为const 成员函数,以便编译器检测您是否意外更新了this。大多数人甚至对 operator+ 使用非成员运算符重载以使其成为对称关系。


不相关,但是:

  • days = h/8;为整数除法(舍去余数)
  • 您的代码似乎同时维持小时,这是脆弱的。似乎只有 hours 应该是一个成员变量,而 getDays 函数(应该是 const)可以即时计算它。
  • 正如 Dan Allen 所指出的,前缀 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
}

关于C++ - 重载 operator+ 接受一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28754450/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com