I am overloading the + operator in C++ to add numbers to an array. I can't add more than one number to the array in one line of code.
This is my + operator method
template<typename Item>
SortedCollection<Item> SortedCollection<Item>::operator+(Item num){
SortedCollection<Item> a;
this -> add(num);
return a;
}
This is the add method in the class it inherits from
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;
In main, the output of this is 19 0 However when I try
one + 19;
one + 9;
cout << one[0] << endl;
cout << one[1] << endl;
It works like intended 19 9 If anyone knows how I can get it to all add on the same line I would appreciate it.
+
is not best choice for such operation. According to principle of "least surprise" +
should not modify its operands. Better to use <<
for example.
That being said you have couple of problems:
a
object, just return *this
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.