c++ 父類與子類的調用關係

#include "stdafx.h"

#include <iostream>

using namespace System;

using namespace std;

class a

{

public:

a(){

std::cout<<"this is a;";

}

virtual void fun();


};

void a::fun()

{

std::cout<<"this is a::fun;";

}

class b:public a

{

public:

b(){

std::cout<<"this is b.";

}

void fun()

{

std::cout<<"this is b:fun"<<std::endl;

}


};

void abtext(a x)

{

x.fun();

}

int main(array<System::String ^> ^args)

{

Console::WriteLine(L"Hello World");

a* x1=new b();

abtext(*x1);


return 0;

}

父類指針指向子類,構造函數調用順序,首先調用父類構造函數,再調用子類構造函數,因此本程序先輸出this is a;再輸出this is b.。完成初始化。調用abtext(*x1);時,由於形參是類a,故應該調用父類的fun()函數,輸出this is a::fun;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章