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

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

出于对齐原因,我使用了一个奇怪的联合。

我已经重载它以便可以为它分配一个字符串值。

现在我想重载 = 运算符,以便我可以将它赋给一个字符串值。

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; }
};

在这种情况下,我们重载了运算符,使得

TextureID t = "hello";

是一个有效的声明。

我如何覆盖 = 运算符才能做到:

string s = t;

您可以创建一个转换运算符,将您的 TextureID 转换为 std::string

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

或者创建一个显式函数来进行转换

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