virtual function

这个是从《Exceptional C++》上看到的,84页,有这么一句话:

Avoid public virtual funtions;prefer using the Template Method pattern instead

这是自己写的几个例子

例1:下面这段代码是没办法编译通过的

#include<iostream>
#include<string>

using namespace std;

class Base
{
private:
    virtual void fun(){cout << "Base" << endl;}
};

class Derived: public Base
{
public:
    void fun(){cout << "Derived" << endl;}
};

int main()
{
    Base* pb=new Derived;
    pb->fun();
    return 0;
}

把例1的代码改成这个,就可以,而且输出我们想要的结果

例2:

#include<iostream>
#include<string>

using namespace std;

class Base
{
public:
    void Print(){fun();}
private:
    virtual void fun(){cout << "Base" << endl;}
};

class Derived: public Base
{
public:
    void fun(){cout << "Derived" << endl;}
};

int main()
{
    Base* pb=new Derived;
    pb->Print();
    return 0;
}

例3:

#include <iostream>
using namespace std;
class a {
public:
  virtual void f() { cout << "a::f" << endl; };
};

class b : public a {
private:
  void f() { cout << "b::f" << endl; };
};

class c : public b {
private:
  void f() { cout << "c::f" << endl; };
};

int main() {
  a* obj = new c();
  obj->f();
  delete obj;
  return 0;
}

这段代码输出的是 c::f

据此,我们是不是该有这样的认识,基类提供接口,继承类提供实现

在这个网站上有关于virtual functions的几个 guideline

http://www.gotw.ca/publications/mill18.htm

#1 prefer to make interfaces novirutal,using Template Method

#2 prefer to make virtual funtion private

#3 only if derived class need to invoke the base implementation of a virtual function,make the virtual protected

#4 A base destructor should be either public and virtual, or protected and no virtual

 

你可能感兴趣的:(virtual function)