C++之private虚函数

一般我们说虚函数,它的访问级别都是public的,用类对象可以直接调用,这样就可以实现运行时的类型绑定,那如果我们将虚函数私有化会出现什么情况呢?

我们先来看一个非虚函数私有化的例子

class Base
{
private:
    void PrintClassName ()
    {
        cout<<"Base"<<endl;
    }
public:
    void print()
    {
        PrintClassName();
    }
};

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

在main函数里产生一个Derived的对象d,然后调用print()函数,即d.print(),结果输出的却是Base,print()函数没有调用子类的PrintClassName函数,而是调用父类的PrintClassName函数,原来是由于PrintClassName函数不是虚函数之故,所以Base的print()函数调用PrintClassName()函数是在编译时就已经绑定了,而不是运行期绑定。

下面我们让PrintClassName()函数变成虚函数再执行,就可以看到输出的类名为子类的名称,即Derived。

那么我们有没有办法调用私有的虚函数呢?当然是有的,不管公有还是私有,只要是虚函数,它的函数地址都会放在虚函数表vftable中,只要我们找到虚函数表中存放的PrintClassName()函数的地址,我们就可以直接调用,前提是你必须对C++类对象的内存布局要熟悉,代码如下,这样也输出Derived,与前面效果相同

int _tmain(int argc, _TCHAR* argv[])
{
    
    Derived d;
    //d.print();
    typedef void (*Fun)();
    Fun pFun = NULL;
    pFun = (Fun)*((int *)(*(int *)&d + 0) + 0);
    pFun();

    getchar();
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++中,虚函数和纯虚函数都是用来实现多态性的特性。虚函数是在基类中声明为虚函数的成员函数,它可以被派生类重写,从而实现运行时多态。而纯虚函数是在基类中声明为纯虚函数虚函数,它没有函数体,需要在派生类中重写实现,从而实现接口的统一。 具体而言,虚函数在基类中使用virtual关键字进行声明,派生类可以通过override关键字重写该虚函数。例如: ```c++ class Animal { public: virtual void makeSound() { std::cout << "Animal makes a sound." << std::endl; } }; class Dog : public Animal { public: void makeSound() override { std::cout << "Woof!" << std::endl; } }; int main() { Animal *animal = new Dog(); animal->makeSound(); delete animal; return 0; } ``` 在这个例子中,Animal类中的makeSound()函数被声明为虚函数,并且在Dog类中被重写。在main函数中,创建了一个Dog对象并将其赋值给Animal指针,然后调用了makeSound()函数,此时会调用Dog类中的makeSound()函数,因为它已经重写了Animal类中的makeSound()函数。 而纯虚函数在基类中使用virtual关键字和=0进行声明,子类必须实现该函数。例如: ```c++ class Shape { public: virtual double getArea() const = 0; }; class Square : public Shape { public: double getArea() const override { return width * width; } private: double width; }; int main() { Shape *shape = new Square(5); std::cout << "Area of square: " << shape->getArea() << std::endl; delete shape; return 0; } ``` 在这个例子中,Shape类中的getArea()函数被声明为纯虚函数,并且在Square类中被实现。在main函数中,创建了一个Square对象并将其赋值给Shape指针,然后调用了getArea()函数,此时会调用Square类中的getArea()函数,因为它已经实现了Shape类中的纯虚函数

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值