#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;
}
输出:
A 构造...
B 构造...
C 构造...
hello I am B Obj.
hello I am C Obj.
hello I am A Obj.
hello I am A Obj.
请按任意键继续. . .
A 析构...
C 析构...
B 析构...
跳过 delete.
.exe (进程 1940)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .
标签:...,可行,Obj,cout,am,C++,pa,Hello,指针
From: https://www.cnblogs.com/huvjie/p/18305194