一.普通指针版本
代码
#include<iostream>
using namespace std;
class A
{
public:
A(){ax=2;cout<<"ax:"<<ax<<endl;};
void print()const;
float ax;
};
class B
{
public:
B();
void print()const;
private:
A* a;
};
B::B()
{
a=new A();
a->ax=3;
}
void B::print()const
{
cout<<"&a="<<&a<<endl;
cout<<"a->ax="<<a->ax<<endl;
}
int main()
{
B b;
b.print();
return 0;
}
运行
二.智能指针版本
代码
#include<iostream>
#include<memory>
using namespace std;
class A
{
public:
A(){ax=2;cout<<"ax:"<<ax<<endl;};
void print()const;
float ax;
};
class B
{
public:
B();
void print()const;
private:
shared_ptr<A> a;
};
B::B()
{
a=shared_ptr<A>(new A());
a->ax=3;
}
void B::print()const
{
cout<<"&a="<<&a<<endl;
cout<<"a->ax="<<a->ax<<endl;
}
int main()
{
B b;
b.print();
return 0;
}
运行
|