简体   繁体   English

C ++-重载“ =”以将十六进制值分配给对象

[英]C++ - Overloading '=' to assign hex value to an object

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. 如果我的理解是正确的,则运算符'='已重载,因此它实际上将十六进制值存储在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将颜色存储在称为“数据”的3字节typedef中)

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM