将对象传递给函数和构造函数中的动态内存分配
Passing objects to functions and dynamic memory allocation in constructors
我的作业是将对象传递给成员函数并在c++中使用构造函数(必须遵循动态内存分配来存储值)。检查下面给出的代码。
#include<iostream>
using namespace std;
class room
{
char *a;
public:
room(string e)
{
a = new char[e.length()];
string a(e);
}
friend void show(room);
};
void show(room z)
{
cout << z.a;
}
int main()
{
string c;
cout << "Enter: ";
cin >> c;
room A(c);
show(A);
}
现在,我希望作为输入的字符串必须在编译代码后由show()打印。
如何修改代码以获得show()的输出??
你的代码中有几个问题:
- 成员a未初始化
- 使用了复制构造函数,但没有实现:show(a) copy a
- 成员a未被释放
修复此问题将得到如下内容:
#include<stdlib.h>
#include<string.h>
#include<iostream>
using namespace std;
class room
{
char *a;
public:
room(string e) : a(strdup(e.c_str())) {};
room(const room &); // not implemented copy construtor
room & operator=(const room &); // not implemented copy operator
~room() { free(a); };
friend void show(const room &);
};
void show(const room & z)
{
cout << z.a;
}
int main()
{
string c;
cout << "Enter: ";
cin >> c;
room A(c);
show(A);
}
但是正如注释中建议的那样,使用std::string来存储值是比char*更好的选择。
相关文章:
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 开放 CV 中的动态内存分配,用于视频处理
- 为什么类和 main() 函数中也有动态内存分配
- 在没有动态内存的世界中,我是否需要虚拟析构函数?
- c++ 动态内存 堆栈中的分配
- 给定特定内存地址的数组的动态内存分配
- 释放动态内存时C++错误
- 我刚刚了解了C++中的动态内存分配
- 无法删除布尔动态内存分配
- 有没有办法找到动态内存大小,比如大小?
- 我在 2D 数组的动态内存分配中遇到了一些奇怪的代码C++? 请解释一下这是什么?
- 具有对齐存储的动态内存分配
- 指向数组unique_ptr在调用 release() 后会自动释放动态内存,这是真的吗?
- 在cpp中使用boost-python的python代码是否进行动态内存分配
- 我应该在这个程序中使用静态内存分配还是动态内存分配
- C++ 模板函数中的动态内存分配
- 指向动态内存中结构中的变量时出现问题
- C++具有动态内存分配的 constexpr 函数
- 动态内存分配错误
- 按引用传递和动态内存分配之间的区别是什么