c++深度拷贝vector

2021-07-11  本文已影响0人  一路向后

1.头文件

#include <iostream>
#include <vector>

class A {
public:
        A(int r);
        A(const A &a);
        ~A();
        void print(A &a);
        void print();
        int x;
        std::vector<A> childs;
};

2.cpp文件

#include "test.h"

using namespace std;

A::A(int r)
{
    x = r;
}

A::A(const A &a)
{
    x = a.x;
    childs = a.childs;
}

A::~A()
{

}

void A::print(A &a)
{
    vector<A>::iterator it;

    cout << "x = " << a.x << endl;

    for(it=a.childs.begin(); it!=a.childs.end(); it++)
    {
        print((*it));
    }
}

void A::print()
{
    print(*this);
}

int main()
{
    A a(10);

    a.childs.push_back(A(11));
    a.childs.push_back(A(12));
    a.childs[0].childs.push_back(A(13));
    a.childs[1].childs.push_back(A(14));

    a.print();

    A b(a);

    cout << "---------------------------------" << endl;

    b.print();

    return 0;
}

3.编译源码

$ g++ -o test test.cpp

4.运行及其结果

$ /test
x = 10
x = 11
x = 13
x = 12
x = 14
---------------------------------
x = 10
x = 11
x = 13
x = 12
x = 14
上一篇 下一篇

猜你喜欢

热点阅读