操作符重载c++在对象中添加int
Operator Overloading c++ adding int to object
我刚刚开始学习操作符重载,并试图理解这个概念。我想重载运算符+。在头文件中有
public:
upDate();
upDate(int M, int D, int Y);
void setDate(int M, int D, int Y);
int getMonth();
int getDay();
int getYear();
int getDateCount();
string getMonthName();
upDate operator+(const upDate& rhs)const;
private:
int month;
int year;
int day;
在我的main中,我创建了一个upDate对象我想把它添加到int类型
upDate D1(10,10,2010);//CONSTRUCTOR
upDate D2(D1);//copy constructor
upDate D3 = D2 + 5;//add 5 days to D2
我该如何写过载,使D2增加5天?我有这个,但我很确定语法是不正确的,错误仍然出现。如有任何帮助,不胜感激
upDate upDate::operator+(const upDate& rhs)const
{
upDate temp;
temp.day = this->day+ rhs.day;
return temp;
}
您需要定义另一个以int型作为实参的操作符+重载:
upDate upDate::operator+(int days) const{
upDate temp(*this);
temp.day += days;
return temp;
}
编辑:正如Dolphiniac所指出的,你应该定义一个复制构造函数来正确初始化temp
。
创建一个复制构造函数来实际复制this
。您的函数正在返回一个对象,该对象通常在this
实例中缺少字段。
重载compound plus
操作符
upDate& upDate::operator+=(const int& rhs)
{
this->day += rhs;
return *this;
}
和
D2 += 5;
相关文章:
- 将布尔变量添加到 int
- 如果 x < 10,则添加前导 0 并将其存储为 int
- "Missing type specifier - int assumed"无法通过向主函数添加"return 0"来解决
- 赋值和添加运算符重载(2个表和int的串联)
- 向size_t添加 int 的正确方法
- C++在减去 int 时向 int 添加一个额外的数字
- 尝试将 char* 添加到 int 时触发编译器错误
- 将map<pair<int,int>,vector<Object> >添加到BST中,其中对是关键
- 如何在类/类型中添加更多函数来构建 int、double、std::string 等
- 当我向 vector<int *> 添加元素时,我遇到了一些问题
- 重载 + 运算符以使用 int 添加对象
- OpenMP增量在线程之间添加int
- 从矢量 c++ 添加 int 元素时出错
- 在c++中添加int数组时,试图找出堆栈损坏的问题
- 使用"uint_64t"添加"int"
- Memcpy:添加int偏移量
- 向数组中添加int,将LSB转换为0 c++
- 向char数组中添加int类型
- 操作符重载c++在对象中添加int
- 使用Rcpp::IntegrVectors添加int