简体   繁体   English

C ++重载运算符=用于字符串

[英]c++ overload operator= for a string

Word Word::operator= (const Word& RHS) const{

    if(word != RHS.GetWord()){
    }
}

I'm at a loss here, how do you effectively delete the current object string, then copy the inputed string to it? 我不知所措,如何有效地删除当前对象字符串,然后将输入的字符串复制到该字符串?

Your error is on the prototype: 您的错误出在原型上:

Word  Word::operator= (const Word& RHS) const{
//  ^                                   ^^^^^ ???

An assignment-operator is useless on a constant object, so the last const is bad. 赋值运算符在常量对象上无用,因此最后一个const不好。
Also, a flaw the compiler cannot diagnose (unless you use it somewhere an lvalue is neccessary), it should return by reference. 同样,编译器无法诊断出一个缺陷(除非您在需要使用左值的地方使用它),它应该通过引用返回。

Anyway, as a member-by-member-copy is good enough, there is no sense in defining your own assignment-operator at all: 无论如何,由于逐成员复制就足够了,因此完全没有必要定义自己的赋值运算符:
Use the default one. 使用默认值。

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

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