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

一种形式:派生类拷贝构造函数名(对象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();
}
posted on 2014-12-22 12:20  Luscinia  阅读(686)  评论(0编辑  收藏  举报