浅谈类的组合

来源:互联网 发布:ledv3.zh3是什么软件 编辑:程序博客网 时间:2024/05/16 15:54

4. 类的组合

4.1 定义

    类中的成员数据是另一个类的对象

 

4.2 类组合的构造函数设计原则

不仅要负责对本类中基本类型成员数据初始化,也要对对象成员初始化。

 

4.3 声明形式

 

类名::类名(对象成员所需的形参,本类成员形参):对象1(参数),对象2(参数),.......

{  // 函数体其他语句 }

 

4.4 例子:类的组合,线段类。

 

#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<<”calling the copy constructor of point”<<endl;

}

Class Line{ //Line类的定义

Public: //外部接口

Line(Point xp1,Point xp2);

Line(Line &l);

double getLen(){return len; }

Private:

Point P1,p2;

double len;   

};

//组合类的构造函数

Line::Line(Point xp1,Point xp2): p1(xp1),p2(xp2){

cout<<”Calling constructor of line”<<endl;

double x = static_cast<double>(p1.getX() - p2.getX());

Double y = static_cast<double>(p1.getY() - p2.getY());

Len = sqrt(x*x+y*y);

}

//组合类的复制构造函数

Line::Line(Line &l):p1(l.p1),p2(l.p2) {

Cout<<”calling the copy constructor of Line”<<endl;

Len = l.len;

}

 

int main()

{

Point myp1(1,1), myp2(4,5); //建立Point类的对象

Line line(myp1,myp2); //建立Line类的对象

//myp1,myp2作为函数实参,传至调用了copy构造,在Line构造函数时,

//初始p1,p2,再次调用copy构造,所以这里总共四次。

 

Line line2(line); //利用复制构造函数建立一个新对象

//在复制构造中,line.p1line.p2去复制给p1,p2.两次copy构造。

cout<<”The length of the line is:”;

cout<<line.getlen()<<endl;

cout<<”The length of the line2 is:”

cout<< line2.getLen()<<endl;

return 0;

}

 

4.5 前向引用声明注意事项

使用前向引用声明虽然可以解决一些问题,但它并不是万能的。需要注意的是,尽管使用了前向引用声明,但是在提供一个完整的类声明之前,不能声明该类的对象,也不能在内联成员函数中使用该类的对象。

例子:

    Class B; //前向引用声明

Class A{

Public:

    Void f(B,b); // 对的,当函数被调用的时候,才会给形参分配内存空间。

              //只有那个时候才要知道B类占多少字节,细节成分。现在

              //定义这个函数原型的时候不需要知道,所以是可以的。

}

Class Fred; //前向声明

Class Barney{

Fred x; //错误:类Fred的声明尚不完善。

}

Class Fred; //前向声明

Class Barney{

Fred  &x; //正确:经过前向引用声明,可以声明Fred类对象的引用。

}

0 0