c++ - 如何避免类里面的破坏

标签 c++ oop

我有一个问题,如何避免类里面的破坏。 我这里有 C++ 示例代码:

class Array {
    int *p;
    int n;
public:
    Array(int n_ = 0) {
        p = new int[n_];
    }
    ~Array(void) { 
        cout << "Deleted" << endl; delete []p;
    }
    friend Array operator+(Array A, Array B)        // the amount of elements A and B are the same
    {
        Array S(A.n);
        for(int i=0; i < A.n; i++)
            S.p[i] = A.p[i] + B.p[i];
        return S;     // object S has been destroyed before returned.
    }
};

在这里,当对象获得值并返回时。但对象S在返回之前已经被销毁了。任何人都可以帮助我避免破坏或者可以通过某种方式将对象 S 返回到 main.谢谢

最佳答案

您可以定义移动和/或复制构造函数(如果未隐式定义),并且该值将在销毁之前移动/复制。

关于c++ - 如何避免类里面的破坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29893126/

相关文章:

Java - 将类的引用传递给另一个类

database-design - 没有 ORM 的领域丰富的应用程序

c++ - OpenCV - 缺少 DLL,但不是吗?

C++,如何将二维 vector 数组传递给函数

c++ - 许多功能的单个 DLL 入口点

java - 关于公共(public)内部类的问题

oop - 什么是 OOP 中的工厂

c++ - QML,Qt 4.8 : How to enable openGl and Chromeless at the same time?

c++ - 无法在虚幻引擎中使用 std::vector

python - PyQt5:通过小部件方法在 QAction 之后更新 MainApplication 布局