组合类、派生类 拷贝构造函数

在派生类中如何写拷贝构造函数

一种形式:派生类拷贝构造函数名(对象p的引用):基类构造函数名(参数列表)

如:student::student(student&p):stud(p.num,p.name,p.sex)
//注意,参数形式,是对象的引用,我们知道引用是C++特有的,这又是一个引用的用法 呵呵

一种形式:派生类拷贝构造函数名(对象p的引用):基类拷贝构造函数名(p)

如:student::student(student &p):stud( p)

注意:在调用基类的构造函数时或拷贝构造函数时,参数一定要干净,啥都不带,就是个参数名,如是数组就写数组名,如是对象,就写对象名!

组合类构造函数一般形式

#include <iostream>
#include<cmath>
using namespace std;
class Point
{
public:
 
Point(int xx=0,int yy=0){X=xx;Y=yy;}
  Point(Point &p);
  int GetX(){return X;}
  int GetY(){return Y;}
private:
  int X,Y;
};
Point::Point(Point &p):X(p.X),Y(p.Y){cout<<”Point拷贝构造函数被调用”<<endl;}
//拷贝构造函数或者可以使用下面的表示方法

//类的组合
  class Line
  {
    public:
      Line(Pointxp1,Point xp2);
      Line(Line&);
      doubleGetLen(){return len;}
    private:
      Pointp1,p2;
      doublelen;
  };

  //组合类的构造函数

  Line::Line(Point xp1,Pointxp2):p1(xp1),p2(xp2)  //构造函数
  {
 
  cout<<”Line构造函数被调用”<<endl;
  double x=double(p1.GetX()-p2.GetX());
  double y=double(p1.GetY()-p2.GetY());
len=sqrt(x*x+y*y);
  }
  //组合类的拷贝构造函数
 
  Line::Line(Line&L):p1(L.p1),p2(L.p2)//拷贝构造函数
  {
  cout<<”Line拷贝构造函数被调用”<<endl;
  len=L.len;
  }
  //主函数
  int main()
  {
  Point myp1(1,1),myp2(4,5);
  Line line(myp1,myp2);
  Line line2(line);
  cout<<”The lengthof the line is:”;
  cout<<line.GetLen()<<endl;
  cout<<”The lengthof the line2 is:”;
  cout<<line2.GetLen()<<endl;
  }

//注意常数据成员只能通过初始化列表来获得初值,如

#include <iostream>
using namespace std;
class A
{
public:
      A(inti);
  void print();
      const int&r;
private:
      const inta;
      static constint b;//静态常数据成员
};
const int A::b=10;//静态常数据成员在类外说明和初始化
A::A(int i):a(i),r(a)    //常数据成员只能通过初始化列表来获得初始值
    {
    }
void A::print()
{
cout<<a<<”:”<<b<<”:”<<r<<endl;
}
int main()
{
A a1(100),a2(0);
a1.print();
a2.print();
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值