我想覆盖运算符'='但是在重载之后,运算符没有将正确的信息传递给对象
I want to overlaod the operator '=' but after the overload the operator doesnt passes the right information to the object
我编写了一个使用运算符重载的类,这样我就可以通过字符串初始化日期。函数中的参数是正确的,但在我将它们传递给对象后,其中有未知的数字(看起来像地址或某个东西(
这是类标题:
#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;
}
相关文章:
- 正在查找文档以获得PS4平台的C++中的设备信息
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 一个关于在C++中重载布尔运算符的问题
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 为什么数组大小信息可用于"sizeof"运算符和 delete[] 运算符,但在将数组作为参数传递到
- 我想覆盖运算符'='但是在重载之后,运算符没有将正确的信息传递给对象
- 编译器在遇到提取或插入运算符时处理信息(字符串、操纵器等)的顺序是什么?
- 如何将上下文信息传递给自定义运算符<<适用于 std::iostream
- 我在 c++ 中的赋值重载运算符有什么问题?(包括详细信息)
- 重载C++新运算符时的大小信息
- C++boost::shared_ptr运算符[]详细信息