細談c++的三大特性
前言:
學習c++之前瞭解c++的三大特性是對c++的整體的認識。
封裝性:
把客觀事物封裝成抽象的類,並且類可以把自己的資料和方法只讓可信的類或者物件操作,對不可信的進行資訊隱藏。 類將成員變數和成員函式封裝在類的內部,根據需要設定訪問許可權,透過成員函式管理內部狀態
class
Person
{
private
:
//資料私有
string
bame
;
int
num
;
public
:
//方法公有
void
getName
()
{
return
name
;
}
};
繼承:
繼承所表達的是類之間相關的關係,這種關係使得物件可以繼承另外一類物件的特徵和能力。 繼承的作用:避免公用程式碼的重複開發,減少程式碼和資料冗餘。
#include
using
namespace
std
;
class
Base
{
public
:
void
printBase
(
void
)
{
cout
<<
“Base中的printBase”
<<
endl
;
}
};
class
Son
:
public
Base
{
};
int
main
(
int
argc
,
char
*
argv
[])
{
Son
ob
;
ob
。
printBase
();
return
0
;
}
執行結果:
多型:
多型性可以簡單地概括為“一個介面,多種方法”,字面意思為多種形態。程式在執行時才決定呼叫的函式,它是面向物件程式設計領域的核心概念。比如函式過載、運算子過載、虛擬函式等
#include
using
namespace
std
;
class
Base
{
public
:
virtual
void
printMsg
(
void
)
{
cout
<<
“Base中的printMsg”
<<
endl
;
}
};
class
Son
:
public
Base
{
public
:
virtual
void
printMsg
(
void
)
{
cout
<<
“Son中的printMsg”
<<
endl
;
}
};
int
main
(
int
argc
,
char
*
argv
[])
{
Base
*
p
=
new
Son
;
p
->
printMsg
();
return
0
;
}
執行結果: