c++虚函数
#pragma once #include <cstring> #include <cstdio> #include <iostream> namespace WYP { class CBase { public: CBase() : m_BaseX(0), m_ptr(NULL) {std::cout << "CBase() is called!" << std::endl;} //如果基类不声明为虚析构函数,析构志向派生类的指针时 不调用 派生类的析构函数 //virtual ~CBase() ~CBase() { std::cout << "~CBase() is called!" << std::endl; } virtual void setBuild(int x) = 0; void bulid(int x) { setBuild(x);//调用派生类的 } void setMemberX(int x) { m_BaseX = x; std::cout << "CBase setMembetX() is called!" << std::endl; } int getMemberX() {return m_BaseX;} virtual void setPtr(int* pInt) {m_ptr = pInt; std::cout << "CBase setPtr() is called!" << std::endl;} virtual int* getPtr() {std::cout << "CBase getPtr() is called!" << std::endl; return m_ptr;} virtual int getInt() {std::cout << "CBase getInt() is called!" << std::endl; return *m_ptr;} virtual void print() {std::cout << m_BaseX << std::endl;} private: int m_BaseX; int* m_ptr; }; class CDivedA : public CBase { public: CDivedA() : m_DivedX(0), m_ptrD(NULL) {std::cout << "CDivedA() is called!" << std::endl;} ~CDivedA() { std::cout << "~CDivedA() is called!" << std::endl; } void Bulitd(int x) { bulid(x); } void setBuild(int x) { m_DivedX = x; std::cout << "CDived setBulid is called!" << std::endl; } void setMemberX(int x) { m_DivedX = x; } void print() {std::cout << m_DivedX << std::endl;} int getMemberX() {return m_DivedX;} void setPtr(int* pInt) {m_ptrD = pInt; std::cout << "CDivedA setPtr() is called!" << std::endl;} int* getPtr() {std::cout << "CDivedA getPtr() is called!" << std::endl;return m_ptrD;} int getInt() {std::cout << "CDivedA getPInt() is called!" << std::endl; return *m_ptrD;} private: int m_DivedX; int* m_ptrD; }; } #include "vitrual.h" using namespace WYP; int main() { //测试析构函数、构造函数调用顺序 /*CBase Base0; CDivedA D0; std::cout << "\n" << "\n" ;*/ //测试虚函数 CBase* pBase = new CDivedA(); int* pInt = new int(5); pBase->setPtr(pInt); std::cout << pBase->getInt() << "\n\n"; pBase->setMemberX(3); std::cout << pBase->getMemberX() << "\n\n"; pBase->bulid(123); pBase->print(); std::cout << "xxxx\n" << "\n" ; delete pBase; //如果基类的析构函数是虚析构函数,则派生类的析构函数被调用,否则,不调用 std::cout << "1\n" << "\n" ; return 0; }