我自己定義了一個字串類 MyStringA ,實作了“operator=”賦值操作,可是在使用的時候卻遇到了以下問題:
1、MyStringA str("Hello World")是可以的。但是MyStringA str="Hello World";卻是不行的
2、除錯錯誤資訊是:error: invalid initialization of non-const reference of type 'MyStringA&' from an rvalue of type 'MyStringA'
想請問一下大神,這個是什么情況?該怎么解決?
uj5u.com熱心網友回復:
class MyStringA
{
public:
MyStringA();
virtual ~MyStringA();
MyStringA(MyStringA& str);
MyStringA(CHAR s[]);
MyStringA(const CHAR* pStr);
MyStringA& operator=(MyStringA& str);
MyStringA& operator=(CHAR* pstr);
MyStringA& operator+(CHAR* pstr);
MyStringA& operator+(MyStringA& str);
MyStringA& operator+=(MyStringA& str);
MyStringA& operator+=(CHAR* pstr);
public:
CHAR* ToString() ;
UINT Length();
protected:
private:
CHAR* psData;
};
uj5u.com熱心網友回復:
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main()
{
MyStringA str("Hello");
cout<<str.ToString()<<endl;
cout<<str.Length()<<endl;
cout<<strlen(str.ToString())<<endl;
MyStringA str2(" World");
str+=str2;
cout<<str.ToString()<<endl;
cout<<str.Length()<<endl;
MyStringA str3="My String Class";
cout<<str3.ToString()<<endl;
cout<<str3.Length()<<endl;
//string str3="My String Class";
//cout<<str3<<endl;
return 0;
}
uj5u.com熱心網友回復:
MyStringA(MyStringA& str);入參加const試試
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/77430.html
標籤:C++ 語言
下一篇:error C141: syntax error near 'led', expected ')'怎么解決,跪求大佬救救我
