c++基础语法 构造函数 析构函数 类的组合

1 构造函数

1.不能指定任何返回值,甚至连void都不能有。

2.与Java不同,c++不同new对象,对于无参的构造函数声明对象时括号应该省略。

 

2 析构函数

1. 前加~,不能有参数,不能有返回值。

2.每个类内只能声明一个析构函数并且公有。

 

3 类的组合

#include <iostream.h>
class A
{
    public:
        A(int x)
        {
            cout<<"class A construing\t\t"<<x<<endl;
        }
        ~A()
        {
            cout<<"class A destroy"<<endl;
        }
};

class B 
{
   public:
        B()
        {
            cout<<"class B construing\t\t"<<endl;
        }
//可以利用这种方式初始化私有变量
        B(int x):b(x)
        {
            //b=x;
            cout<<"class B construing\t\t"<<b<<endl;        
        }
        ~B()
        {
            cout<<"class B destroying"<<endl;
        }
    private:
        int b;
};

class C
{
    public:
        C(int x,int y):a1(y)
        {
            cout<<"Class A with y ,C with xy construing, but B with nothing "<<x<<y<<endl;
        }
        C(int x,int a,int b);
        ~C()
        {
            cout<<"class C destroying"<<endl;
        }
        private:
            A a1;
            B b1;
};

C::C(int x,int a,int b):b1(b),a1(a)
{
    cout<<"class A B C construing"<<x<<a<<b<<endl;  
}

int main()
{
    C c1(2,3);
    C c2(4,5,6);
    return 0;
}

 

创建组合类时,将按内嵌对象在类中的声明先后顺序,而不是按成员初始化列表中的顺序,调用其相应的构造函数,最后调用该组合类的构造函数。

析构函数的调用正好相反。

定义构造函数时,才可以带有成员的初始化列表,如果仅是声明构造函数,不可以带成员初始化列表。

必须指出成员初始化列表也可用于初始化类中的普通数据成员。

posted @ 2015-12-19 21:48  小德cyj  阅读(784)  评论(0编辑  收藏  举报