2015-10-18 33 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; 
}