I have a solution for you and a warning for your operator overload.
Solution:
#include <iostream>
using namespace std;
struct Element {
double d;
Element(double d) {this->d = d;}
Element operator*(const Element &obj) {
d *= obj.d;
return *this;
}
};
Element operator*(const int i, const Element& e) {
return Element(static_cast<double>(i) * e.d);
}
ostream& operator<<(ostream& os, const Element& e) {
os << e.d;
return os;
}
int main() {
Element e(2);
cout << "Product of 8 and e: " << 8*e << '\n';
// This shows why your overload is a bad idea:
Element a(3);
cout << "a is " << a << '\n'; // prints 3
cout << "Now its product with e is: " << a*e << '\n'; // prints 6
cout << "Surprise: a is now " << a << '\n'; // prints 6
}
Your original overload did not work, cause it wasn't even called. Your expression was similar to
a = 8*c
where 8 is of type int and when C++ parses this expression from left to right it sees that 8 is of type int and tries to search for an overload of operator*(const Element&) in the type int and it cannot find it, cause it does not know and is not supposed to know anything about your own user-defined type. So if you want your own class to interact with the other types you either need to embed an overload of operator* as a member function into that other type or declare it as the external function like I did in my solution.
Now the warning. Your original operator overload is ill-defined, cause it modifies the original object, which is considered to be an unexpected behavior. I show this in the code above. It's like multiplying 8 by 2 would give you 16, but at the same time make 16 out of your 8. What you really want to do is to create a new element in your multiplication operator and return it:
struct Element {
double d;
Element(double d) {this->d = d;}
Element operator*( const Element &obj) {
return Element(this->d * obj.d);
}
};
Damn these answers take heck a lot of time... I should be working though :\