封装一个c风格的缓冲区
Encapsulates a C-style Buffer
我有下面的代码来说明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;
}
相关文章:
- C++字符*缓冲区的大小
- Qt VTK交互风格的信号到小部件
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- ostream过载时的缓冲区冲洗
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 我可以使用条件运算符初始化C风格的字符串文字吗
- Visual Studio 2019:插入多个C++风格的单行注释
- Xaudio2在更改缓冲区或循环时弹出声音
- 为什么我在leetcode上收到AddressSanitizer:地址0x602000000058上的堆缓冲区溢出错误
- 如何将图像传输到c++(dll)中的缓冲区,然后在c#的缓冲区中读/写
- 如何在本地机器上运行c++和javascript客户端代码(hackerbank风格)
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 多线程双缓冲区
- Android P-9.0.0_r53 Logcat主缓冲区超出定义大小
- 套接字读取后,我在缓冲区中看到意外输入
- std::带有自定义缓冲区的 iostream 不允许我写入
- 封装一个c风格的缓冲区
- 在结构体中复制一个c++风格的缓冲区
- 内存管理——用于分配/释放I/O缓冲区的现代c++风格