构造函数名(形参表): 基类名(基类构造函数实参表)
{
...
}
#include <iostream>
#include <string>
using namespace std;
class CBug {
int legNum, color;
public:
CBug(int ln, int c1) : legNum(ln), color(c1)
{
cout << "CBug Constructor" << endl;
};
~CBug()
{
cout << "CBug Destructor" << endl;
}
void Printlnfo()
{
cout << legNum << "," << color << endl;
}
};
class CFlyingBug : public CBug
{
int wingNum;
public:
//CFlyingBug(){} 若不注释掉则会编译出错
CFlyingBug::CFlyingBug(int ln, int c1, int wn) : CBug(ln, c1), wingNum(wn)
{
cout << "CFlyingBug Constructor" << endl;
}
~CFlyingBug()
{
cout << "CFlyingBug Destructor" << endl;
}
};
int main() {
CFlyingBug fb(2, 3, 4);
fb.Printlnfo();
return 0;
}
程序输出结果:
#include <iostream>
using namespace std;
class A {
public:
int n;
A(int i) :n(i) { cout << "A " << n << " constructed" << endl; }
~A() { cout << "A " << n << " destructed" << endl; }
};
class B :public A
{
public:
B(int i) :A(i) { cout << "B constructed" << endl; }
~B() { cout << "B destructed" << endl; }
};
class C :public B {
public:
C() :B(2) { cout << "B constructed" << endl; }
~C() { cout << "B destructed" << endl; }
};
int main()
{
C Obj;
return 0;
}
程序的输出结果:
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有