简体   繁体   English

对运算符C ++感到困惑

[英]confused about operators c++

here is the operator function(inSeconds is of type int) 这是运算符函数(inSeconds是int类型)

const Time Time::operator +( const Time& t) const {
    return Time(inSeconds_ + t.inSeconds_);
}

but i need to also make this code work with this operator. 但我还需要使此代码与此运算符一起工作。 (t1 being an instance of time and 12 being an integer) without swapping the values in the the order) (t1是时间的实例,12是整数),而无需按顺序交换值)

Time t(12 + t1);

please help me, sorry if this made no sense im a newbie. 请帮助我,对不起,如果这对新手没有意义。

thanks 谢谢

  1. Make the function a global function, not a member function. 使函数成为全局函数,而不是成员函数。
  2. Add a constructor to Time that takes an int (representing seconds) as an argument. 将一个构造函数添加到Time ,该构造函数以int (代表秒)作为参数。

The following code works for me: 以下代码对我有用:

struct Time
{
   Time(int sec) : inSeconds_(sec) {}
   int inSeconds_;
};

Time operator+(Time const& lhs, Time const& rhs)
{
   return Time(lhs.inSeconds_ + rhs.inSeconds_);
}

int main()
{
   Time t1(10);
   Time t2(12 + t1);
}

What you need is a free function operator. 您需要一个自由函数运算符。

struct Time {
  // ...
};

// note: outside the class

Time operator+(const Time& left, const int& right)
{
  return Time( /* whatever should go here */);
}

Always prefer to write binary operators as free functions that do their work in terms of utility methods on the class - your life will be easier. 始终喜欢将二进制运算符编写为自由函数,这些自由函数根据类上的实用程序方法来完成其工作-您的生活会更轻松。

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

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