重写std::string的赋值(=)操作符

C++ Overriding assignment ( = ) operator of std::string

本文关键字:操作符 std string 重写 赋值      更新时间:2023-10-16

我真的不是要重写它,因为我知道这是不可能的(除非我自己做)。但是我要怎么做呢

strText = "bla bla";
strText.Compile();    //<--- I want this one to be implicitly call.

我知道我可以用这样的方法来做

updateText(const std::string& text)
{
    strText = text;
    Compile();
}

std::string& updateText()
{
    Compile();      //hmm not sure about this. never try
    return strText;
}

但是是否有其他的技术可以通过只执行

来实现这个隐式操作呢?
strText = newText;   //<--automatically call the `Compile()`

? ?

请在我把它交给updateText()之前让我知道

谢谢!

我能想到的唯一解决方案是定义my::string(在内部存储std::string以提供基本的字符串功能)并定义:

my::string(const char*);

为了允许C风格字符串和my::string之间的隐式转换,然后定义:

my::string& operator=(const char*);

实现Compile函数的调用