gpt4 book ai didi

c++ - 二进制 '=' : no operator found which takes a right-hand operand (or there is no acceptable conversation)

转载 作者:行者123 更新时间:2023-11-30 03:14:28 26 4
gpt4 key购买 nike

我在重载运算符“=”的特定代码部分的标题中提到了一个错误。 “=”似乎可以独立工作,但当我将“=”运算符与“+”运算符结合使用时,事情会变得一团糟

主要.cpp:

#include "MyString.h"
#include <iostream>

int main() {

char String1[] = "abcdef";
MyString NewString(String1);

char String2[] = "cd";
MyString SubString(String2);

cout << NewString.GetStringLength() << endl;
cout << SubString.GetStringLength() << endl;
NewString = (SubString + SubString); // Here I get an error
cout << NewString.GetStringLength() << endl;

system("pause");
return 0;
}

类构造函数和运算符:

    MyString::MyString() {
StringLength = 0;
Pointer = nullptr;
}

MyString::MyString(const char* String) {
for (int i = 0; String[i]; i++)
StringLength++;
Pointer = new char[StringLength + 1];
char *Source = (char *)String;
char *Destination = (char *)Pointer;
for (int i = 0; i < StringLength + 1; i++)
Destination[i] = Source[i];
}

MyString::MyString(int Length)
:Pointer(new char[Length + 1]), StringLength(Length) {
Pointer[Length] = 0;

MyString MyString::operator=(MyString &String) {
int BigLength;
int SmallLength;
this->StringLength > String.StringLength ?
BigLength = this->StringLength, SmallLength = String.StringLength :
BigLength = String.StringLength, SmallLength = this- >StringLength;
this->StringLength = String.StringLength;
for (int i = 0; i < SmallLength - 1; i++)
this->Pointer[i] = String.Pointer[i];
for (int i = SmallLength; i < BigLength - 1; i++)
this->Pointer[i] = 0;
return *this;
};

MyString MyString::operator+(MyString &String) {
MyString TempString(this->StringLength + String.StringLength);
for (int i = 0; i < this->StringLength; i++)
TempString.Pointer[i] = this->Pointer[i];
for (int i = 0; i < String.StringLength; i++)
TempString.Pointer[i + this->StringLength] = String.Pointer[i];
return TempString;
};

最佳答案

返回的临时对象

(SubString + SubString)

不能绑定(bind)到左值引用 - MyString::operator=(MyString &String)

复制赋值运算符应通过const Lvalue reference获取其参数:

MyString::operator=(const MyString &String)

关于c++ - 二进制 '=' : no operator found which takes a right-hand operand (or there is no acceptable conversation),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57832805/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com