通过使用不同的构造函数创建对象,并最终释放对象的内存

creating objects by using different constructors and freeing memory of the objects in the end

本文关键字:释放 内存 对象 构造函数 创建对象      更新时间:2023-10-16

我有以下代码:

#include <iostream>
#include <cstring>
using namespace std;
// Class declaration
class NaiveString {
    private:
        char *str;
    public:
        NaiveString(const char*);
        NaiveString(const NaiveString&);
        void update(char, char);
        void print();
};
// Constructors
NaiveString::NaiveString(const char* t) {
    str = new char[strlen(t) + 1];
    strcpy(str, t);
    cout << "First constructor is being invoked." << endl;
}
NaiveString::NaiveString(const NaiveString& src) {
    str = new char[strlen(src.str) + 1];
    strcpy(str, src.str);
    cout << "Second copy constructor is being invoked." << endl;
}
// Methods
/* The following method replaces occurrences of oldchar by newchar */
void NaiveString::update(char oldchar, char newchar) {
    unsigned int i;
    for (i = 0; i < strlen(str); i++) {
        if (str[i] == oldchar) {
            str[i] = newchar;
        }
    }
}
/* The following method prints the updated string in the screen */
void NaiveString::print() {
    cout << str << endl;
}
// Function
void funcByVal(NaiveString s) {
    cout << "funcbyval() being called" << endl;
    s.update('B', 'C');
    // Printing the results
    s.print();
}
int main() {
    NaiveString a("aBcBdB");
    a.print();
    NaiveString b("test, second object");
    b.print();
    cout << "About to call funcbyval(): " << endl;
    // Calling funcByVal
    funcByVal(a);
    // Printing the results
    a.print();

    return 0;
}

和上述代码的这个问题:

基于上面的源代码,实现方法funcByref()。然后在你的主函数使用不同的构造函数创建至少两个对象,调用funcByVal()、funcByRef(),并在屏幕上打印结果。然后确保对象占用的内存在节目结束时发布。

我已经创建了这两个对象,但它们当前使用的是相同的构造函数。我该怎么做才能让他们使用不同的构造函数?此外,我如何创建funcByRef()并调用它?最后,如何在程序结束时释放对象占用的内存?

期待您的回答。

感谢

如果想要调用第二个构造函数,但要向其传递char*,则需要传递NaiveString&像这个

NaiveString a("aBcBdB");
a.print();
NaiveString b(a);   // a is a NaiveString reference here
b.print();

funcByRef()就是这样的,只需通过引用传递即可

void funcByRef(NaiveString& s){
    s.update('B', 'C');
    s.print();
}

最后,为了释放你的字符串,你需要创建一个像这样的析构函数

NaiveString::~NaiveString()
{
    delete[] str;
}

我该怎么做才能让他们使用不同的构造函数?

这是没有必要的。你为什么认为你需要这个?

此外,我如何创建funcByRef()并调用它?

网上有很多资源描述了如何在C++中通过引用传递。请参阅c++中的函数"按值调用"answers"按引用调用"作为示例。

最后,如何在程序结束时释放对象占用的内存?

没有什么可做的。将为每个对象调用析构函数,这将释放任何内存。你们班还没有这样做。看什么是三条规则?了解更多信息。

我该怎么做才能让他们使用不同的构造函数?

为了调用不同的构造函数,必须重载它们,这可以通过使用不同的参数列表来实现。

例如,在类中,有两个不同的构造函数,其中一个接收字符串,另一个接收对对象的引用。

因此,您可以通过向其中一个构造函数传递不同类型的参数来调用它

此外,我如何创建funcByRef()并调用它?

我想象funcByRef应该接收到对对象的引用,比如

void funcByRef(NaiveString& s)
{
    s.update(A,B);
    s.print();
}

最后,如何在程序结束时释放对象占用的内存?

一开始你不需要释放内存,因为你的程序完成了,整个内存堆栈无论如何都会被释放。然而,我假设这是某种分配,因此,为了释放内存,您应该调用delete。如:

delete a;
delete b;

但是,请注意,delete调用了类的析构函数,而该类并没有定义。默认的析构函数可能会错过char数组。因此,在析构函数中,必须从该数组中释放内存。我会说:

~NaiveString()
{
    delete str;
}