我必须将 String 重新定义为类,并且对 operator+ 重载或复制构造函数有疑问。我的 main() 编译但不返回任何内容或涂鸦。这是 String 类的片段:
class String {
char *nap;
public:
String(const char* ns){
nap=strcpy(new char[strlen(ns)+1],ns);
}
String(const String & n){
nap=strcpy(new char[strlen(n.nap)+1],n.nap);
}
String operator+(const String& n) const;
String operator+(const char* ns) const;
//operator=
String& operator=(const String &n){
if(this==&n)
return *this;
delete []nap;
nap= strcpy(new char[strlen(n.nap)+1],n.nap);
return *this;
}
//...
friend String operator+(const char*, const String&);
friend ostream& operator<<(ostream&, const String&);
};
String String::operator+(const String& s) const{
return String(nap+*s.nap);
}
String String:: operator+(const char* c) const{
return String(nap+*c);
}
String operator+(const char* c,const String & s){
return String(String(s)+String(c));
}
ostream &operator<<(ostream& os,const String& s){
os<<s.nap<<endl;
return os;
}
这里是主要的:
String s ="To "+String("be ") + "or not to be";
cout<<s<<endl;
最佳答案
class String {
char *nap;
public:
// Default argument is nifty !!
String(const char* ns=""){
nap=strcpy(new char[strlen(ns)+1],ns);
}
// !! Don'te forget to delete[] on destruction
~String() {
delete[] nap;
}
String(const String & n){
nap=strcpy(new char[strlen(n.nap)+1],n.nap);
}
String operator+(const String& n) const;
// Not necessary since String(const char *) exists
// an expression like String+"X" will be casted to String+String("X")
// String operator+(const char* ns) const;
//operator=
String& operator=(const String &n){
if(this==&n)
return *this;
delete []nap;
nap= strcpy(new char[strlen(n.nap)+1],n.nap);
return *this;
}
//...
friend String operator+(const char*, const String&);
friend std::ostream& operator<<(std::ostream&, const String&);
};
// Make enough space for both strings
// concatenate
// !! delete the buffer
String String::operator+(const String& si) const {
char *n = new char [strlen(nap)+strlen(si.nap)+1];
strcpy(n,nap);
strcpy(n+strlen(nap),si.nap);
String so = String(n);
delete [] n;
return so;
}
// Not necessary. Since String(const char *) exists
// String String:: operator+(const char* c) const{
// return String(nap+*c);
// }
String operator+(const char* c,const String & s){
return String(String(s)+String(c));
}
std::ostream &operator<<(std::ostream& os,const String& s){
os<<s.nap<<std::endl;
return os;
}
关于c++ - 将字符串重新定义为类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34952485/