将字符串重新定义为类

Redefining String as class

本文关键字:定义 字符串 新定义      更新时间:2023-10-16

我必须将字符串重新定义为类,并且在运算符+重载或复制构造函数时遇到问题。我的main()编译,但没有给出任何回报或涂鸦。这是类字符串的片段:

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;
}

在你的运算符+中调用strcat(或更好的strncat),而不是添加指针。或者通过将一个小睡的字节复制到另一个小睡的末尾来自己做。在这两种情况下,您都必须确保分配了足够的内存!

加法运算符对我来说看起来不正确。

*运算符可以读作 的内容。所以*s.nap实际上是s.nap的内容,这是一个char,表示nap指向的第一个字符。所以nap+*s.nap不是你想要的,nap+*c也不是.

您还需要类的析构函数,以确保删除nap指向的内存。