簡體   English   中英

對運算符C ++感到困惑

[英]confused about operators c++

這是運算符函數(inSeconds是int類型)

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

但我還需要使此代碼與此運算符一起工作。 (t1是時間的實例,12是整數),而無需按順序交換值)

Time t(12 + t1);

請幫助我,對不起,如果這對新手沒有意義。

謝謝

  1. 使函數成為全局函數,而不是成員函數。
  2. 將一個構造函數添加到Time ,該構造函數以int (代表秒)作為參數。

以下代碼對我有用:

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);
}

您需要一個自由函數運算符。

struct Time {
  // ...
};

// note: outside the class

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

始終喜歡將二進制運算符編寫為自由函數,這些自由函數根據類上的實用程序方法來完成其工作-您的生活會更輕松。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM