是否会动态联编,只看基类的那个函数是否有virtual,派生类里有没有virtual没关系
下面是测试的代码
#pragma once #ifndef TEST_H_ #define TEST_H_ //basic class class test { private: int x; public: test(int a = 0); test(const test & a); virtual void show() const; //void show() const; //virtual ~test(); }; //derived class class testp : public test { private: int y; public: testp(int a = 0, int b = 0); testp(const test & a, int b); //virtual void show() const; void show() const; //virtual ~testp(); }; #endif // !TEST_H_ //输出记录 //当两个都有关键字virtual时,调用的是派生类的show //当基类有virtual,派生类testp没有virtual时,调用的是仍然是派生类的show //当基类没有virtual,派生类有virtual时候,调用的是基类的show //当都没有virtual时,调用的是基类的virtual //总结,是否需要动态联编看的是基类的virtual,跟派生类的是否为virtual没有关系
#include"test.h" #include<iostream> using std::cout; using std::endl; test::test(int a) { x = a; } test::test(const test & a) { x = a.x; } void test::show() const { cout << x << ' '; } testp::testp(int a, int b) : test(a) { y = b; } testp::testp(const test & a, int b) : test(a) { y = b; } void testp::show() const { test::show(); cout << ", " << y; }
#include"test.h" #include<iostream> using namespace std; int main() { testp op(1, 3); //derived class object op.show(); cout << endl; test * p; //base class pointer //*p = op; //为什么这里用*会报错?是因为没有初始化//指针一定要记得初始化一个地址,不能直接用*p,要先& p = &op; p->show(); cout << endl; return 0; }
浙公网安备 33010602011771号