2015-10-18 35 views
0

我有下面的代碼來說明C風格的字符串。這段代碼僅用於說明。構造函數正確地初始化實例,但是在閱讀MyString廢話時會回來。任何人都可以建議或解釋什麼是錯的?封裝一個C風格的緩衝區

#include <iostream> 
using namespace std; 

class MyString 
{ 
private: 
    char* Buffer; 
public: 
    //Constructor 
    MyString(const char* InitialInput) 
    { 
     char* Buffer = new char [4]; // Only three characters are allowed! 
             // It must end with '\0' or it is not a string 
     for(int i=0 ; i<3 ; ++i){ 
      Buffer[i]=InitialInput[i]; 
     } 
     Buffer[3]='\0';     // Now it is a string. 

     cout << "Constructed the string: " << Buffer << endl; 

    } 

    void ShowString() 
    { 
     cout << "This is the string: " << Buffer << endl; 
    } 
}; 

int main() { 
    MyString line1("abc"); // Only three characters are allowed! 
    MyString line2("def"); 

    cout << endl << "MyString objects: " << endl; 
    line1.ShowString(); 
    line2.ShowString(); 


    return 0; 
} 

這是回來的畫面

構建的字符串上:ABC

構建的字符串:DEF

MyString的對象:

這是字符串:ƒä [<°°)@

這是s tring:「ÿ(

+0

析構函數是你的朋友,不泄漏內存 – AndrewBloom

回答

2

問題是您在構造函數的本地作用域中定義了char *Buffer。因此,不使用數據成員,而是使用局部變量。這裏是正確的代碼

class MyString 
{ 
private: 
    char* Buffer; 
public: 
    //Constructor 
    MyString(const char* InitialInput) 
    { 
     //char* Buffer -> dont define here. If defined, this definition 
     //will hide the data member defintion 
     Buffer = new char [4]; // Only three characters are allowed! 
             // It must end with '\0' or it is not a string 
     for(int i=0 ; i<3 ; ++i){ 
      Buffer[i]=InitialInput[i]; 
     } 
     Buffer[3]='\0';     // Now it is a string. 

     cout << "Constructed the string: " << Buffer << endl; 

    } 

    void ShowString() 
    { 
     cout << "This is the string: " << Buffer << endl; 
    } 
}; 

int main() { 
    MyString line1("abc"); // Only three characters are allowed! 
    MyString line2("def"); 

    cout << endl << "MyString objects: " << endl; 
    line1.ShowString(); 
    line2.ShowString(); 


    return 0; 
}