[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;
}
[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;
}
[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;
}