gpt4 book ai didi

c++ - 封装一个 C 风格的缓冲区

转载 作者:行者123 更新时间:2023-11-28 02:18:52 25 4
gpt4 key购买 nike

<分区>

我有下面的代码来说明 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 对象:

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

这是字符串:”ÿ(

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com