思想: 将类的指针成员附加对其引用次数封装到一个“智能指针类Point”中,定义类成员指向这个Point类。 1 #include <string> 2 using namespace std; 3 class Product; 4 class Point 5 { 6 friend class Product; 7 private: 8 string *ip; 9 size_t use; 10 public: 11 Point(string *p):ip(p),use(1){} 12 ~Point(){delete ip;} 13 }; 14 class Product 15 { 16 private: 17 int name; 18 Point *point; 19 20 public: 21 Product(string* p):point(new Point(p)),name(1){} 22 Product(const Product & p):point(p.point),name(p.name) 23 { 24 ++point->use;//copy constructor,inc the use size 25 } 26 Product & operator = (const Product & p) 27 { 28 ++p.point->use; 29 if(--point->use == 0) 30 delete point;//when copy,first del privious "use" 31 //copy 32 this->name = p.name; 33 this->point = p.point; 34 return *this; 35 36 } 37 int get_name() 38 { 39 return name; 40 } 41 string get_ip() 42 { 43 return *point->ip; 44 } 45 void set_name() 46 { 47 name = 1; 48 } 49 void set_ip(string s) 50 { 51 *point->ip= s; 52 } 53 ~Product() 54 { 55 --point->use; 56 if(point->use == 0) 57 delete point;//deconstructor,dec the use size 58 59 } 60 }; main.cpp 1 #include "test.h" 2 #include <iostream> 3 int main() 4 { 5 //string s("shh"); 6 string* s = new string("shh"); 7 Product p1(s); 8 // Product p2(p1); 9 Product p2 = p1; 10 p1.set_ip("abc"); 11 cout << p2.get_ip() <<endl; 12 }