简体   繁体   English

如何在C ++中重载赋值运算符的两个方向?

[英]How to overload both directions of an assignment operator in C++?

I have a weird union I am using for alignment reasons. 由于对齐原因,我使用了一个奇怪的工会。

I have overloaded it so that it can be assigned a string value. 我已经对其进行了重载,以便可以为其分配一个字符串值。

Now I wish to overload the = operator so that I can assign it TO a string value. 现在,我希望重载=运算符,以便可以将其分配给字符串值。

union Tag
{
    std::string * path;
    long id;
};
struct TextureID
{
    Tag ID;
    int type;

    TextureID& operator= (std::string str){ ID.path = new std::string(str); type=0; }
    TextureID& operator= (long val){ ID.id = val; type=1; }
};

In this case we have overloaded the operators such that 在这种情况下,我们使运算符超载,从而

TextureID t = "hello";

Is a valid statement. 是有效的声明。

How may I overwrite the = operator to be able to do: 我该如何覆盖=运算符才能执行以下操作:

string s = t;

You can create a conversion operator to convert your TextureID to a std::string 您可以创建一个转换运算符,将您的TextureID转换为std::string

operator std::string() const {
    // logic to create a string to return
}

or create an explicit function to do the conversion 或创建一个显式函数进行转换

std::string to_string() const {
    // logic to create a string to return
}

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

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