#include <iostream>
using namespace std;
class Box {
public:
double getVolume(void) {
return length * breadth * height;
}
void setLength( double len ) {
length = len;
}
void setBreadth( double bre ) {
breadth = bre;
}
void setHeight( double hei ) {
height = hei;
}
// Overload + operator to add two Box objects.
Box operator+(const Box& b) {
Box box; //local object?
box.length = this->length + b.length;
box.breadth = this->breadth + b.breadth;
box.height = this->height + b.height;
return box;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The source of the code: https://www.tutorialspoint.com/cplusplus/cpp_overloading.htm. How does the above operator+ work? What I'm confused is that as opposed to Java, in C++ Box box creates an object on the stack, but the method is returning the object whose lifetime is limited to that scope of method (operator).
So I tried another example:
template <typename T>
class SmartPointer
{
T *ptr;
int numElem; //-1 if an element. >=0 if an array
public:
SmartPointer(T pNum);
SmartPointer();
SmartPointer(T *pArray, int pSize);
~SmartPointer();
SmartPointer(std::initializer_list<T> nums);
T getValue() const;
T getValue(int index) const;
void setValue(T pNum);
void setValue(T pNum, int index);
int getNumElem() const;
SmartPointer<T> operator+ (const SmartPointer<T>& ptr);
SmartPointer<T> operator- (const SmartPointer<T>& ptr);
SmartPointer<T> operator* (const SmartPointer<T>& ptr);
};
template <class T>
SmartPointer<T> SmartPointer<T>::operator+ (const SmartPointer<T>& p_ptr)
{
int pSize = this->getNumElem();
T tempArray[pSize] = {0};
for(int i = 0; i < this->getNumElem(); i++)
{
int result = this->getValue(i) + p_ptr.getValue(i);
tempArray[i] = result;
}
SmartPointer<T> result(tempArray, pSize); (line 60)
return result; (line 61)
}
}
I am trying to implement smartpointer, and I want to overload + as if it were a componentwise addition (like vector addition).
Then, if I run the following code:
SmartPointer<int> sPointer6({10,11,12});
SmartPointer<int> sPointer7({10,11,12});
SmartPointer<int> sPointer8 = sPointer6 + sPointer7;
cout << sPointer8.getValue(0) << endl; //getValue(index)
cout << sPointer8.getValue(1) << endl;
cout << sPointer8.getValue(2) << endl;
I get the following output:
1310912
1338712
24
But if I replace line 60 and line 61 by
return SmartPointer<T>(tempArray, pSize);
Then I get the following output:
20
22
24
Why am I getting different outputs? And why does the first example work but not the smartpointer example?
Aucun commentaire:
Enregistrer un commentaire