#include <iostream>
#include <memory>
using namespace std;
class A;
class B
{
public:
B(shared_ptr<A> a)
{
pa = a;
cout << "B 构造..." << endl;
}
~B()
{
cout << "B 析构..." << endl;
}
shared_ptr<A> pa;
public:
void Hello()
{
cout << "hello I am B Obj." << endl;
}
};
class C
{
public:
C(shared_ptr<A> a)
{
pa = a;
cout << "C 构造..." << endl;
}
~C()
{
cout << "C 析构..." << endl;
}
shared_ptr<A> pa;
public:
void Hello()
{
cout << "hello I am C Obj." << endl;
}
};
class A
{
public:
A()
{
cout << "A 构造..." << endl;
self = shared_ptr<A>(this, [](A* a) { cout << "跳过 delete." << endl; });
pb = make_shared<B>(self);
pc = make_shared<C>(self);
}
~A()
{
cout << "A 析构..." << endl;
}
shared_ptr<B> pb;
shared_ptr<C> pc;
private:
shared_ptr<A> self;
public:
void Hello()
{
cout << "hello I am A Obj." << endl;
}
};
int main()
{
auto a = make_shared<A>();
a->pb->Hello();
a->pc->Hello();
a->pb->pa->Hello();
a->pc->pa->Hello();
system("pause");
return 0;
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
- 78.
- 79.
- 80.
- 81.
- 82.
- 83.
- 84.
- 85.
输出:
多文件拆分
A.h
A.cpp
#include "A.h"
#include <iostream>
A::A()
{
std::cout << "A 构造..." << std::endl;
self = std::shared_ptr<A>(this, [](A* a) { std::cout << "跳过 delete." << std::endl; });
pb = std::make_shared<B>(self);
pc = std::make_shared<C>(self);
}
A::~A()
{
std::cout << "A 析构..." << std::endl;
}
void A::Hello()
{
std::cout << "hello I am A Obj." << std::endl;
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
B.h
B.cpp
C.h
C.cpp
main.cpp
输出: