拷贝构造函数

#include<iostream>
using namespace std;


class F{
int n;
int d;
public:
F(int n = 0,int d = 1);//默认构造函数(无参)
//这俩也算重载
void print(bool newline = true);
void print(bool newline = true)const;//表示函数对当前对象的操作是只读的,此函数的当前对象是只读的
void input();
~F();
F(const F &f):n(f.n),d(f.d)//拷贝构造函数(本类)
{cout<<this<<"F(F)"<<n<<"/"<<d<<endl;}
};
F::F(int n,int d):n(n),d(d)//初始化列表的表示方式为 成员变量名(初始值)
{
cout<<this<<' '<<"F("<<n<<","<<d<<")\n";
}
F::~F()
{
cout<<this<<' '<<"~F()"<<n<<'/'<<d<<endl;
}
void F::print(bool newline)const
{
cout<<"(只读的)"<<n<<'/'<<d;
if(newline) cout<<endl;
}
void F::print(bool newline)
{
cout<<"(自由的)"<<n<<'/'<<d;
if(newline) cout<<endl;
}


int compare(const F &x,const F &y)
{
x.print();
y.print();
}
F func(F x){return x;}
int main()
{
F d(3,5);
func(d);

F* p = new F;//C++里不建议用malloc返回void*的类型   F* q = static_cast<F*>(malloc(sizeof(F)));不会调用构造函数
F a(1,2),b(3,4);
a.print();
b.print();
delete p;//free(q);不会调用析构函数
F *q = new F[4];
for(int i = 0;i<4;i++) q[i].print(false);
cout<<endl;
delete[] q;
p = new F(8,15);
const F c(5,6);
//c.input(); //有const 修饰的对象只能调用const 成员函数

delete p;p = NULL;
cout<<"==================="<<endl;
compare(a,b);
cout<<"==================="<<endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值