I'm trying to implement a system similar to color object hex assignment, such as:
Color color;
color = 0xffff00;
If my understand is correct the operator '=' has been overloaded so it actually stores the hex value in a datatype inside Color. I don't really understand how to do this, but here's what I have: (assume Color stores color in a 3 byte typedef called "data")
Color operator=(const unsigned int& c) {
Color color;
color.data = c;
return color;
}
Would this give me what I need?
I think it would be better to implement it as a member function, so it can modify the object in place rather than constructing a new one and copying it.
class Color {
...
public:
void operator= (const unsigned int &c) {
data = c;
}
...
}
You should overload the assignment operator of the class and probably a constructor as well like this:
class Color
{
public:
Color(): data(0) {}
Color(unsigned i): data(i) {} // add an int constructor
// add assignment operator
Color& operator=(unsigned i) { data = i; return *this; }
private:
unsigned data;
};
Overloading the constructor allows you to do initialization like this:
Color c = 0x00FF00;
Overloading the assignment operator allows you assign after initialization:
c = 0xFF00FF;
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.