封装一个c风格的缓冲区

Encapsulates a C-style Buffer

本文关键字:风格 缓冲区 一个 封装      更新时间:2023-10-16

我有下面的代码来说明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 '' or it is not a string
        for(int i=0 ; i<3 ; ++i){
            Buffer[i]=InitialInput[i];
        }
        Buffer[3]='';                 // 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对象:

这是字符串:ƒÄ[Ã1Ûë‰Ã?C[…°)@

这是字符串:"¾(

问题是您在构造器的局部作用域中定义了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 '' or it is not a string
        for(int i=0 ; i<3 ; ++i){
            Buffer[i]=InitialInput[i];
        }
        Buffer[3]='';                 // 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;
}