求助,c++一些问题。
有个程序是关于运算符重载的,编译后一直报错,大概就是“=”重载后编译器找不到,求解决;[Error] no match for 'operator=' (operand types are 'Str' and 'Str')
还有个问题是 函数声明的时候;比如 char& operator[] (int); 返回值类型为啥前面有个&,char& 是个什么意思?
求解;
程序代码:
#include<iostream> #include<cstdlib> #include<cstring> using namespace std; class Str { char *p; public: Str(); Str(char *s); ~Str(); Str(Str&); Str& operator=(Str&); char& operator[] (int); Str operator+(Str&); int operator==(Str&); int operator>(Str&); int operator<(Str&); friend istream& operator>>(istream&,Str&); friend ostream& operator<<(ostream&,Str&); } ; Str::Str() { p=NULL; } Str::Str(char *s) { p=new char[strlen(s)+1]; strcpy(p,s); } Str::~Str() { if(p) delete []p; } Str::Str(Str &str) { if(str.p) { p=new char[strlen(str.p)+1]; strcpy(p,str.p); } else p=NULL; } Str& Str::operator=(Str &str) { if(this==&str) return *this; if(p) delete []p; p=new char[strlen(str.p)+1]; strcpy(p,str.p); return *this; } char& Str::operator[](int n) { static char ch; if(n>strlen(p)) { cout<<"超出边界!"<<endl; return ch; } return *(p+n); } Str Str::operator+(Str &str) { Str stradd; stradd.p=new char[strlen(p)+strlen(str.p)+1]; strcpy(stradd.p,p); strcat(stradd.p,str.p); return stradd; } int Str::operator==(Str &str) { if(strcmp(p,str.p)==0) return 1; else return 0; } int Str::operator>(Str &str) { if(strcmp(p,str.p)>0) return 1; else return 0; } int Str::operator<(Str &str) { if(strcmp(p,str.p)<0) return 1; else return 0; } istream& operator>>(istream &in,Str &str) { char s[100]; cout<<"请输入字符串对象的内容:"; in.getline(s,100); if(str.p) delete []str.p; str.p=new char[strlen(s)+1]; strcpy(str.p,s); return in; } ostream& operator<<(ostream &out,Str &str) { out<<str.p; return out; } int main() { Str s1,s2,s3; cout<<"字符操作演示!"<<endl; cout<<"输入两个字符串类的对象,观察运算结果!"<<endl; cin>>s1>>s2; s3=s1+s2; cout<<s1<<'+'<<s2<<'='<<s3<<endl; if(s1>s2) cout<<s1<<'>'<<s2<<endl; else if(s1<s2) cout<<s1<<'<'<<s2<<endl; else cout<<s1<<'='<<s2<<endl; cout<<"实现下标运算符操作"<<endl; int n; cout<<"请输入一个整数:"; cin>>n; cout<<"s1["<<n<<"]="<<s1[n]<<endl; cout<<"s2["<<n<<"]="<<s2[n]<<endl; s1[1]='a'; s2[1]='b'; cout<<"s1="<<s1<<endl; cout<<"s2="<<s2<<endl; return 1; }