📄 multiinheritance1.html
字号:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<link rel="stylesheet" href="css/stdlayout.css" type="text/css">
<link rel="stylesheet" href="css/print.css" type="text/css">
<meta content="text/html; charset=gb2312" http-equiv="content-type">
<title>多重继承(一)</title>
</head>
<body>
<h3><a href="http://caterpillar.onlyfun.net/GossipCN/index.html">From
Gossip@caterpillar</a></h3>
<h1><a href="CppGossip.html">C++
Gossip: 多重继承(一)</a></h1>
C++允许让衍生类别同时直接继承两个以上的父类别,例如有A、B两个类别,您可以使用下面的方式来让C类别直接继承这两个类别: <br>
<div style="margin-left: 40px; font-weight: bold; font-family: Courier New,Courier,monospace;">class C : public A, public B { <br>
public: <br>
C(int x) : A(x), B(x) { // 多重继承下的建构函式呼叫 <br>
// 实作 <br>
} <br>
<br>
// 实作 <br>
};<br>
</div>
<br>
上面也同时示范了在继承之后的的建构函式呼叫,没有参数的预设建构函式不用使用这种方式执行,它会自动被呼叫,而解构函式也是会自动执行。 <br>
<br>
多重继承之后的建构函式执行顺序,是依您撰写程式时的顺序由左而右决定,最后才是继承后衍生类别,例如上面的例子中,会先执行A类别定义的建构函式,然后
再执行B类别的建构函式,最后执行C类别的建构函式,而解构函式的执行则正好相反,先执行衍生类别的解构函式,然后再右向左执行,使用下面这个简单的范例
来示范: <br>
<br>
<pre>#include <iostream> <br>using namespace std; <br><br>class FooA { <br>public: <br> FooA() { <br> cout << "执行FooA建构函式" << endl;<br> } <br><br> ~FooA() { <br> cout << "执行FooA解构函式" << endl;<br> } <br>}; <br><br>class FooB { <br>public: <br> FooB() { <br> cout << "执行FooB建构函式" << endl;<br> } <br><br> ~FooB() { <br> cout << "执行FooB解构函式" << endl;<br> } <br>}; <br><br>class FooC : public FooA, public FooB { <br>public: <br> FooC() { <br> cout << "执行FooC建构函式" << endl;<br> } <br><br> ~FooC() { <br> cout << "执行FooC解构函式" << endl;<br> } <br>}; <br><br>int main() { <br> FooC c; <br><br> cout << endl; <br><br> return 0;<br>}</pre>
<span class="postbody"><br>
执行结果:</span><br>
<table style="text-align: left; width: 100%;" border="0" cellpadding="2" cellspacing="2">
<tbody>
<tr>
<td style="background-color: rgb(0, 0, 0);"><small><span style="color: rgb(255, 255, 255);">执行FooA建构函式 <br>
执行FooB建构函式 <br>
执行FooC建构函式 <br>
<br>
执行FooC解构函式 <br>
执行FooB解构函式 <br>
执行FooA解构函式</span></small><span style="color: rgb(255, 255, 255);"><br>
</span></td>
</tr>
</tbody>
</table>
<br>
<br>
<br>
</body>
</html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -