C++ 覆盖 std::string 的赋值 ( = ) 运算符

标签 c++ string

我真的不是说要覆盖它,因为我知道这是不可能的(除非我自己做)。但是我该怎么做才能像这样

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函数的调用。

关于C++ 覆盖 std::string 的赋值 ( = ) 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16788837/

相关文章:

c++ - 使用 if(true) 子句缩小资源管理器对象的范围?

c++ - 重载运算符 < 比较字符串,使用 string.compare 对链表进行排序?

c - 当 C 中需要 unsigned int 时,将字符串传递给函数

c++ - 在 C++ 构造函数中初始化数组

Java:通过名称调用和访问数组,该名称存储在不同数组或变量内的字符串中

c++ - 将字符串传递给 file.open();

c# - 如何访问列表中的随机项目?

c++ - OpenGL 跨平台窗口

c++ - 如何正确设置 std::complex<mpf_class> 的精度并读取它?

c++ - 为什么在linux上用久了物理内存一直在增加,虚拟内存大小会增加一点