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

标签 c++ object constructor

我有以下代码:

#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;
}

上面代码的这个问题:

Based on the above source code, implement the method funcByref(). Then in your main function create at least two objects using the different constructors, call funcByVal(), funcByRef(), and print the results on the screen. Then make sure that the memory occupied by the objects will be released by the end of the program.

我已经创建了 2 个对象,但它们目前使用相同的构造函数。我该怎么做才能让他们使用不同的构造函数? 另外,如何创建 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;
}

关于c++ - 通过使用不同的构造函数创建对象并最终释放对象的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33979405/

相关文章:

C++ 无法使用 g++-mp-4.4 捕获从 Mac OS 中的 curlpp 抛出的异常

c# - 如何从捕获的异常中打印消息?

c++ - 在一个循环中证明内存访问

c++ - 从基类构造函数调用纯虚函数

c++ - 输入\输出文件编译错误

javascript - arr.pop() 从其他数组中弹出元素

object - 检查vbscript中是否设置对象

javascript - 如何交换数组的格式? - JavaScript

c++ - 避免在构造函数中分配或保持简单性(和 RAII?)

java - java中构造函数的返回类型是什么?