简体   繁体   English

C ++重载加法运算符以添加对象

[英]C++ Overloading addition operator to add objects

I'm working on a project where I need to add two objects together by overloading the addition operator, 99% of it makes sense to me, but I can't figure out how to do the actual addition process. 我正在一个项目中,我需要通过重载加法运算符来将两个对象加在一起,其中99%对我来说是有意义的,但我不知道如何进行实际的加法过程。

My code is currently 我的代码是当前

Time operator+(const Time& t1)
{
     int num = this.milliseconds + t1.milliseconds;
     Time t(num);
     return t;
}

Then I call it like so 然后我这样称呼它

t4 = t1 + t2;

I thought using this.milliseconds would allow me to access t1 's int variable but it won't allow me. 我以为使用this.milliseconds将允许我访问t1的int变量,但不允许我使用。

Basically my question is how do I access the time variable on the left of the + operator since I only pass the operator+ function one object of Time? 基本上,我的问题是,由于我只将operator +函数传递给Time的一个对象,因此如何访问+运算符左侧的时间变量? (t2) (T2)

If your operator+ is a member function of the Time class then you should be able to access its fields when you change this.milliseconds to this->milliseconds or just milliseconds . 如果您的operator+Time类的成员函数,那么当您将this.milliseconds更改为this->milliseconds或just milliseconds时,您应该能够访问其字段。 Please note that this is a pointer so it requires the -> operator. 请注意, this是一个指针,因此需要->运算符。

You don't have to be concerned about the operator+ having only one parameter. 您不必担心operator+仅具有一个参数。 If you overload a two argument operator as a class member then it is implicitly assumed that the first argument of the operator is this . 如果将两个参数运算符重载为类成员,则隐式假定该运算符的第一个参数是this

You have also a possibility to overload an operator as a non-member function and then you have to specify two parameters like this: Time operator+(const Time& t1, const Time& t2) . 您还可以将运算符作为非成员函数重载,然后必须指定两个参数,例如: Time operator+(const Time& t1, const Time& t2)

It is also worth mentioning that your operator+ could be a const member function. 还值得一提的是,您的operator+可以是const成员函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM