我想覆盖运算符'='但是在重载之后,运算符没有将正确的信息传递给对象

I want to overlaod the operator '=' but after the overload the operator doesnt passes the right information to the object

本文关键字:运算符 信息 对象 之后 覆盖 重载      更新时间:2023-10-16

我编写了一个使用运算符重载的类,这样我就可以通过字符串初始化日期。函数中的参数是正确的,但在我将它们传递给对象后,其中有未知的数字(看起来像地址或某个东西(

这是类标题:

#include <iostream>;
using namespace std;
class Date {
private:
public:
int day;
int month;
int year;
Date();
Date(int day, int month, int year);
void Print(Date date);
Date operator=(const string str);
};

这是cpp类文件:

#include "Date.h"
Date::Date() {};
Date::Date(int day, int month, int year) :
day(day),month(month), year(year){};
void Date::Print(Date date) {
cout << date.day << "/" << date.month << "/" << date.year;
}
Date Date::operator=(string str) {
Date date;
date.day = 0; date.month = 0; date.year = 0;
int i = 0;
while(str[i] != '/'){
date.day = (10 * date.day) + (int)str[i++]- 48;
}
i++;
while(str[i] != '/'){
date.month = (10 * date.month) + (int)str[i++]- 48;
}
i++;
while(i < str.size()){
date.year = (10 * date.year) + (int)str[i]- 48;
i++;
}
cout << date.day << '/' << date.month << '/' << date.year<< endl;
return date;
}

这是主要的:

#include <iostream>
#include "Date.h"
using namespace std;
int main() {
Date d,d2(15,7,18);
string str = "15/7/18";
d = str;
cout << d.day<< endl;
d.Print(d);
return 0;
}

您不是在修改curect对象,而是在修改一个名为date的变量。从重载运算符中删除date变量。像这个

Date& Date::operator=(string str) {
day = 0; month = 0; year = 0;
int i = 0;
while(str[i] != '/'){
day = (10 * day) + (int)str[i++]- 48;
}
...
return *this;
}

此外,operator=通常应返回一个引用,即Date&

最好更改您的operator=签名:

Date& operator=(const std::string& str);

在您的实现中,您正在修改类型为Date的本地对象,而不是为其调用方法的对象。你可以这样修改:

Date& Date::operator=(const std::string& str) {
this->day = 0; this->month = 0; this->year = 0;
int i = 0;
while(str[i] != '/'){
this->day = (10 * this->day) + (int)str[i++]- 48;
}
i++;
while(str[i] != '/'){
this->month = (10 * this->month) + (int)str[i++]- 48;
}
i++;
while(i < str.size()){
this->year = (10 * this->year) + (int)str[i]- 48;
i++;
}
std::cout << this->day << '/' << this->month << '/' << this->year<< std::endl;
return *this;
}