封装C风格的缓冲区

时间:2015-10-18 10:38:44

标签: c++ string oop

我有下面的代码来说明C样式字符串。这段代码仅供参考。构造函数正确初始化实例,但是当读取MyString时,废话会回来。任何人都可以建议或解释什么是错的?

#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对象:

这是字符串:ƒÄ[ÃÛÛë‰Ã?C <...°] @

这是字符串:“ÿ(

1 个答案:

答案 0 :(得分: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;
}