I am trying to create the operator that makes the same thing as constructor do.
I have created the overloaded output operator << for this class , it was easy.
I just wanna type nameOfObject+(value) to create new instance of foo class.
I tried this:
foo& operator+(int x, foo& f) {
f tmp = new foo(x);
return tmp;
}
But I got error message that says I need to use ; after tmp;
#include <iostream>
#include <memory>
class foo {
private:
int x;
public:
foo(int x) { this->x = x; }
int getX() { return this->x; }
};
std::ostream& operator<< (std::ostream& text, foo& f) {
text << f.getX();
return text;
}
int main()
{
foo bar(2);
std::cout <<bar; //returns 2
return 0;
}
UPDATE_1:
For example, I have the heightOfTheTree variable in my class. Using foo tree1(5) - normal constructor I just want to assign the 5 to my variable. But using foo tree2+5, I want to create new object with value multiplied twice(for example).