operator= from class to some other type
I have a simple question, to which I couldn't find a direct answer.
If I have a class:
1 2 3 4 5 6
|
template <typename T>
class myClass
{
T x;
};
|
How does the prototype of operator= look like if I want to make the following code compilable:
1 2 3 4
|
double t;
myClass<double> cls;
t = cls;
|
so that after the last line, I'll have t = cls.x automatically. Is that possible?
Thank you for any efforts.
As far as i know it's impossible because operator= has to be a member of a class.
Instead you could make use of the cast operator:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
#include <iostream>
using namespace std;
class test {
public:
double A;
operator double() { return A; }
};
int main(int argc, char **argv) {
test tt;
tt.A = 4.;
double k = tt;
cout << k;
return 0;
}
|
This prints 4 to standart output.
Thanks a lot, man! That's exactly what I was looking for :)
Cheers!
Topic archived. No new replies allowed.