Part4 类与对象 4.4析构函数 4.5类的组合

析构函数:完成对象被删除前的一些清理工作。
在对象的生存期结束的时刻系统自动调用它,然后再释放此对象所属的空间。
如果程序中未声明析构函数,编译器将自动产生一个默认的析构函数,其函数体为空。

构造函数和析构函数举例:

#include 
using namespace std;
class Point {     
public:
    Point(int xx,int yy);
    ~Point();//析构函数没有参数,没有返回值
    //...其他函数原型
private:
    int x, y;
};

Point::Point(int xx, int yy){
    x = xx;
    y = yy;
}
Point::~Point(){
}
//...其他函数的实现

 

 


4.5类的组合
组合的概念:类中的成员是另一个类的对象。

类组合的构造函数设计
原则:不仅要负责对本类中的基本类型成员数据初始化,也要对对象成员初始化。

声明形式:
类名::类名(对象成员所需的形参,本类成员形参):
对象1(参数),对象2(参数),......
{
//函数体其他语句
}

 

构造组合类对象时的初始化次序:
首先对构造函数初始化列表中列出的成员(包括基本类型成员和对象成员)进行初始化,初始化次序是成员在类体中定义的次序。
  成员对象构造函数调用顺序:按对象成员的声明顺序,先声明者先构造。
  初始化列表中未出现的成员对象,调用用默认构造函数(即无形参的)初始化
处理完初始化列表之后,再执行构造函数的函数体。

//类组合程序举例,类的组合,线段(Line)类
#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{//线段类
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);
    Line line(myp1, myp2);
    Line line2(line);//利用复制构造函数建立一个新对象
    cout << "The length of the line is: ";
    cout << line.getLen() << endl;
    cout << "The length of the line2 is: ";
    cout << line2.getLen() << endl;
    return 0;
}

 

 

前向引用声明:
  类应该先声明,后使用
  如果需要在某个类的声明之前,引用该类,则应进行前向引用声明。
  前向引用声明只为程序引入一个标识符,但具体声明在其他地方。

class B;  //前向引用声明
class A {
public:
    void f(B b);
};
class B {
public:
    void g(A a);
};

在提供一个完整的类声明之前,不能声明该类的对象,也不能在内联成员函数中使用该类的对象。
当使用前向引用声明时,只能使用被声明的符号,而不能涉及类的任何细节。

class Fred; //前向引用声明
class Barney {
    Fred x; //错误:类Fred的声明尚不完善
};
class Fred {
    Barney y;
};

 

posted @ 2017-11-30 14:38  LeoSirius  阅读(177)  评论(0编辑  收藏  举报