C++ 智能指针 和 继承多态 的实现
Test.h 头文件
1 #ifndef TestNameSpace_TestClass 2 #define TestNameSpace_TestClass 3 //#define public public: 4 //#define private private: 5 //#define protected protected: 6 7 extern "C" 8 { 9 namespace TestNameSpace 10 { 11 class Test{ 12 public: void Method1(); 13 public: void Method2(); 14 15 public: void Method3(); 16 protected: virtual void Method4(); 17 }; 18 19 class TestA : public Test 20 { 21 void Method4(); 22 }; 23 }; 24 }; 25 26 #endif
Test.cpp 函数实现
1 #include <iostream> 2 #include "Test.h" 3 using namespace std; 4 5 void TestNameSpace::Test::Method1() 6 { 7 cout<<"Method1"<<endl; 8 } 9 10 void TestNameSpace::Test::Method2() 11 { 12 cout<<"Method2"<<endl; 13 } 14 15 void TestNameSpace::Test::Method3() 16 { 17 cout<<"Call Method4()"<< endl; 18 this->Method4(); 19 } 20 21 void TestNameSpace::Test::Method4() 22 { 23 cout<<"Method4"<<endl; 24 } 25 26 27 28 29 void TestNameSpace::TestA::Method4() 30 { 31 cout<<"Method444444444"<<endl; 32 33 }
Program.cpp 运行调用
1 #include <iostream> 2 #include <memory> 3 #include "Test.h" 4 using namespace std; 5 using namespace TestNameSpace; 6 7 int main(){ 8 9 cout<<"AAAA"<<endl; 10 11 shared_ptr<Test> test = std::make_shared<TestA>(); 12 test->Method1(); 13 test->Method2(); 14 test->Method3(); 15 16 17 Test *test2 = new TestA(); 18 test2->Method1(); 19 test2->Method2(); 20 test2->Method3(); 21 delete test2; 22 23 Test test3; 24 test3.Method1(); 25 test3.Method2(); 26 test3.Method3(); 27 28 cin.get(); 29 };
运行结果: