簡體   English   中英

如何重載 + 運算符以在一行中將多個變量添加到數組

[英]How do I overload the + operator to add multiple variables to an array in one line

我在 C++ 中重載 + 運算符以將數字添加到數組。 我不能在一行代碼中向數組添加多個數字。

這是我的 + 運算符方法

template<typename Item>
SortedCollection<Item> SortedCollection<Item>::operator+(Item num){
  SortedCollection<Item> a;
  this -> add(num);
  return a;
 }

這是它繼承自的class中的add方法

template<typename Item>
void Collection<Item>::add(Item e) {
    if (curSize == capacity) {
      expand();
    }
    elements[curSize] = e;
    curSize++;
}
SortedCollection<int> one;
 one + 19 + 9 + 2 + 8 + 7 + 12  + 17 + 0 + 11 + 6 + 3 + 1;
 cout << one[0] << endl;
 cout << one[1] << endl;

總的來說,這個 output 是 19 0 但是當我嘗試

one + 19;
one + 9;
cout << one[0] << endl;
cout << one[1] << endl;

它像預期的那樣工作 19 9 如果有人知道我如何將它添加到同一行,我將不勝感激。

+不是此類操作的最佳選擇。 根據“最少意外”的原則+不應修改其操作數。 最好使用<<例如。

話雖這么說,你有幾個問題:

  1. 操作員應返回對 object 的引用,而不是 object 的副本。
  2. 無需a object,只需返回*this即可。

暫無
暫無

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

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