我编写了一个使用运算符重载的类,因此我可以通过字符串初始化日期。函数中的参数是正确的,但是当我将它们传递给对象后,其中的数字未知(看起来像地址或东西)
这是类标题:
#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;
}
答案 0 :(得分:2)
您不是在修改当前对象,而是在修改名为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&
。
答案 1 :(得分:0)
最好更改您的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;
}