簡體   English   中英

將String重新定義為類

[英]Redefining String as class

我必須將String重新定義為類,並且遇到運算符+重載或復制構造函數的問題。 我的主要()編譯,但沒有提供任何東西或塗鴉作為回報。 這是類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;

在運算符+中調用strcat (或更好的strncat )而不是添加指針。 或者通過將一個小睡的字節復制到另一個小睡來完成。 在這兩種情況下,您必須確保分配了足夠的內存!

添加運算符對我來說不正確。

*運算符可以作為內容讀取。 所以*s.nap實際上是s.nap的內容,它是一個char表示由nap指向的第一個字符。 所以nap+*s.nap不是你想要的,也不是nap+*c

您還需要一個類的析構函數,以確保刪除內存nap點。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM