将对象传递给函数和构造函数中的动态内存分配

Passing objects to functions and dynamic memory allocation in constructors

本文关键字:动态 内存 分配 构造函数 对象 函数      更新时间:2023-10-16

我的作业是将对象传递给成员函数并在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*更好的选择。