1.不能指定任何返回值,甚至連void都不能有。
2.與Java不同,c++不同new對象,對於無參的構造函數聲明對象時括號應該省略。
1. 前加~,不能有參數,不能有返回值。
2.每個類內只能聲明一個析構函數並且公有。
#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;
}
創建組合類時,將按內嵌對象在類中的聲明先後順序,而不是按成員初始化列表中的順序,調用其相應的構造函數,最後調用該組合類的構造函數。
析構函數的調用正好相反。
在定義構造函數時,才可以帶有成員的初始化列表,如果僅是聲明構造函數,不可以帶成員初始化列表。
必須指出成員初始化列表也可用於初始化類中的普通數據成員。
