给基类中的构造函数传递参数的通用形式如下:derived-constructor(arg-list) : base1(arg-list), base2(arg-list), baseN(arg-list);
{
//函数体;
} 上面的形式中,派生类构造函数声明和基类之间是用冒号分隔。在又多个基类的情况下,积累之间以逗号分隔。如下程序所示:
[C++] 纯文本查看 复制代码
#include <iostream>
using namespace std;
class base {
protected:
int i;
public:
base(int x) { i = x; cout << "Constructing base\n"; }
~base() { cout << "Destructing base\n"; }
};
class derived: public base {
int j;
public:
//派生类使用x; y 被传递给 base 的构造函数
derived(int x, int y): base(y)
{
j = x;
cout << "Constructing derived\n";
}
~derived() { cout << "Destructing derived\n"; }
void show() { cout << i << " " << j << endl; }
};
int main()
{
derived ob(3, 4);
ob.show();
return 0;
}
运行输出:$ ./passargtobase
Constructing base
Constructing derived
4 3
Destructing derived
Destructing base 上面程序中,derived 的构造函数里有两个参数 x 和 y 。derived() 只用了参数 x,参数 y 被传递给了基类构造函数 base() 。一般情况下,在派生类的构造函数中,除了声明该类需要的参数外,还必须声明基类需要的参数。
下面程序是派生类从多个基类中继承的示例:
[C++] 纯文本查看 复制代码
#include <iostream>
using namespace std;
class base1 {
protected:
int i;
public:
base1(int x) { i = x; cout << "Constructing base\n"; }
~base1() { cout << "Destructing base\n"; }
};
class base2 {
protected:
int k;
public:
base2(int x) { k = x; cout << "Constructing base2\n"; }
~base2() { cout << "Destructing base2\n"; }
};
class derived: public base1, public base2 {
int j;
public:
derived(int x, int y, int z): base1(y), base2(z) //注意 y 和 z 的传递
{
j = x;
cout << "Constructing derived\n";
}
~derived() { cout << "Destructing derived\n"; }
void show() { cout << i << " " << j << " " << k << endl; }
};
int main()
{
derived ob(3, 4, 5);
ob.show();
return 0;
}
运行输出:$ ./passargtobase2
Constructing base
Constructing base2
Constructing derived
4 3 5
Destructing derived
Destructing base2
Destructing base 在传递参数给基类构造函数的一个重点是:基类构造函数中的参数是通过派生类的构造函数传递的。基于此,像上面的程序,假如派生类的构造函数 derived() 并不要求带有任何参数,但如果基类的构造函数需要带有一个或多个参数,那么它就必须声明这些参数。如下代码所示:
[C++] 纯文本查看 复制代码
#include <iostream>
using namespace std;
class base1 {
protected:
int i;
int j;
public:
base1(int x, int y) { i = x; j = y; cout << "Constructing base\n"; }
~base1() { cout << "Destructing base\n"; }
};
class base2 {
protected:
int k;
public:
base2(int x) { k = x; cout << "Constructing base2\n"; }
~base2() { cout << "Destructing base2\n"; }
};
class derived: public base1, public base2 {
public:
derived(int x, int y, int z): base1(x, y), base2(z)
{
cout << "Constructing derived\n"; //该构造函数不需要带有参数
}
~derived() { cout << "Destructing derived\n"; }
void show() { cout << i << " " << j << " " << k << endl; }
};
int main()
{
derived ob(3, 4, 5);
ob.show();
return 0;
}
运行输出:$ ./passargtobase3
Constructing base
Constructing base2
Constructing derived
3 4 5
Destructing derived
Destructing base2
Destructing base |