C++继承机制下的构造函数
生活随笔
收集整理的這篇文章主要介紹了
C++继承机制下的构造函数
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
派生類同樣有構(gòu)造函數(shù)。當(dāng)我們創(chuàng)建一個(gè)派生類對(duì)象的時(shí)候,基類構(gòu)造函數(shù)將會(huì)被自動(dòng)調(diào)用,用于初始化派生類從基類中繼承過來的成員變量。而派生類中新增的成員變量則需要重新定義構(gòu)造函數(shù)用于初始化了。
#include<iostream> using namespace std;class book { public:book();book(char* a, double p = 5.0);void setprice(double a);double getprice()const;void settitle(char* a);char * gettitle()const;void display(); private:double price;char * title; };class book_derived :public book { public:book_derived(){cout<<"book_derived 構(gòu)造函數(shù)"<<endl;}void display(); };book::book(char* a, double p) {title = a;price = p; }book::book() {cout<<"book 構(gòu)造函數(shù)"<<endl;title = "NoTitle";price = 0.0; }void book::setprice(double a) {price = a; }double book::getprice()const {return price; }void book::settitle(char* a) {title = a; }char * book::gettitle()const {return title; }void book::display() {cout<<"book The price of "<<title<<" is $"<<price<<endl; }void book_derived::display() {cout<<"book_derived The price of "<<gettitle()<<" is $"<<getprice()<<endl; }int main() {book_derived b;b.display();return 0; } 運(yùn)行結(jié)果: book 構(gòu)造函數(shù) book_derived 構(gòu)造函數(shù) book_derived The price of NoTitle is $0創(chuàng)建對(duì)象時(shí)先是執(zhí)行基類的構(gòu)造函數(shù),然后再是執(zhí)行派生類構(gòu)造函數(shù)。構(gòu)造函數(shù)執(zhí)行順序是按照繼承順序自頂向下執(zhí)行。
?
總結(jié)
以上是生活随笔為你收集整理的C++继承机制下的构造函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++名字隐藏
- 下一篇: C++派生类构造函数调用规则