65,210
社区成员
发帖
与我相关
我的任务
分享
class A
{
public:
A():p(NULL){};
~A(){};
int* p;
};
int main(int argc,char* argv[])
{
A a;
a.p = new int(5);
A b ;
b = a;
cout<<a.p<<":"<<*(a.p)<<endl;
cout<<b.p<<":"<<*(b.p)<<endl;
return 0;
}
程序实例如下:
#include <iostream>
using namespace std;
class Cat
{
public:
Cat();
Cat(const Cat &);
~Cat();
int GetAge() const { return *itsAge; }
int GetWeight() const { return *itsWeight; }
void SetAge(int age) { *itsAge=age; }
private:
int *itsAge; //实际编程并不会这样做,
int *itsWeight; //我仅仅为了示范
};
Cat::Cat()
{/*构造函数,在堆中分配内存*/
itsAge=new int;
itsWeight=new int;
*itsAge=5;
*itsWeight=9;
}
Cat::Cat(const Cat & rhs)
{/*copy constructor,实现深层复制*/
itsAge=new int;
itsWeight=new int;
*itsAge=rhs.GetAge();
*itsWeight=rhs.GetWeight();
}
Cat::~Cat()
{
delete itsAge;
itsAge=0;
delete itsWeight;
itsWeight=0;
}
int main()
{
Cat Frisky;
cout << "Frisky's age: "<<Frisky.GetAge()<<endl;
cout << "Setting Frisky to 6...\n";
Frisky.SetAge(6);
cout << "Create Boots from Frisky\n";
Cat Boots=Frisky; //or Cat Boots(Frisky);
cout << "Frisky's age: " <<Frisky.GetAge()<<endl;
cout << "Boots' age : "<<Boots.GetAge()<<endl;
cout << "Set Frisky to 7...\n";
Frisky.SetAge(7);
cout << "Frisky's age: "<<Frisky.GetAge()<<endl;
cout << "Boots' age: "<<Boots.GetAge()<<endl;
return 0;
}
//输出:
//Frisky's age: 5
//Setting Frisky to 6...
//Create Boots from Frisky
//Frisky's age: 6
//Boots' age : 6
//Set Frisky to 7...
//Frisky's age: 7
//Boots' age: 6