2015-06-17 29 views
0

明天我想爲我的測試做一個示例考試,但遇到了一個小問題,這可能是一個愚蠢的錯誤。有一個類包含一個char*,它包含一個C字符串和一個包含該字符串長度的int。現在我需要做一些類似class[5] = 'd'的工作。但我不知道如何。我知道我可以重載[]運算符以返回指向字符串特定字母的指針,但我無法直接指定charC++運算符重載,兩次

我的代碼:

#include <iostream> 
#include <string> 

using namespace std; 

class DynString 
{ 
private: 
    char * _theString; 
    int _charCount; 

public: 
    DynString(char * theString = nullptr) { 
     if(theString == nullptr) 
      _charCount = 0; 
     else { 
      _charCount = strlen(theString); 
      _theString = new char[strlen(theString) + 1]; // +1 null-terminator 
      strcpy(_theString, theString); 
     } 
    } 

    char* operator[](int index) { 
     return &_theString[index]; 
    } 

    DynString operator+(const DynString& theStringTwo) { 
     DynString conCat(strcat(_theString, theStringTwo._theString)); 
     return conCat; 
    } 

    void operator=(const DynString &obj) { 
     _theString = obj._theString; 
     _charCount = obj._charCount; 
    } 

    friend ostream& operator<< (ostream &stream, const DynString& theString); 
    friend DynString operator+(char * ptrChar, const DynString& theString); 

}; 

ostream& operator<<(ostream &stream, const DynString& theString) 
{ 
    return stream << theString._theString; 
} 

DynString operator+(char * ptrChar, const DynString& theString) { 
    char * tempStor = new char[strlen(ptrChar) + theString._charCount + 1] ;// +1 null-terminator 
    strcat(tempStor, ptrChar); 
    strcat(tempStor, theString._theString); 

    DynString conCat(tempStor); 
    return conCat; 
} 


int main() 
{ 
    DynString stringA("Hello"); 
    DynString stringB(" Worlt"); 
    cout << stringA << stringB << std::endl; 

    stringB[5] = 'd'; // Problem 

    DynString stringC = stringA + stringB; 
    std::cout << stringC << std::endl; 

    DynString stringD; 
    stringD = "The" + stringB + " Wide Web"; 
    std::cout << stringD << std::endl; 

    return 0; 
} 
+2

讓你的'operator []'返回一個'char&'並相應地改變你的return語句。 –

+0

非常感謝! –

+0

我還建議檢查請求索引是否超過實際字符串的長度,如果有,則拋出異常。 –

回答

0

有點示範。

#include <iostream> 
#include <string.h> 
using namespace std; 

class String 
{ 
private: 
    char *data; 
    int length; 
public: 
    String(const char * str) 
    { 
     data = new char[strlen(str)]; 
     strcpy(data, str); 
     length = strlen(data); 
    } 
    char &operator[](int index) 
    { 
     //dont forget to check bounds 
     return data[index]; 
    } 
    int getLength() const 
    { 
     return length; 
    } 
    friend ostream & operator << (ostream &out, String &s); 
}; 
ostream &operator << (ostream &out, String &s) 
{ 
    for (int i = 0; i < s.getLength(); i++) 
     out << s[i]; 
    return out; 
} 
int main() 
{ 
    String string("test"); 
    string[1] = 'x'; 

    cout << string; 

    return 0; 
}