我怎样才能访问派生类私有方法?

问题描述 投票:2回答:1

下面的代码让我可以访问派生类的私有成员函数。据我所知,一个班级的私人成员无法通过任何方式访问。下面的代码如何能够访问派生类私有方法?

#include "stdafx.h"
#include <iostream>

using namespace std;

class Base
{
public:
    virtual void function()
    {
        cout << __FUNCTION__ << endl;
    }
};

class Derived : public Base
{
private:
    void function()
    {
        cout << __FUNCTION__ << endl;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    Base * b = new Derived();
    b->function();
    delete b;
}

输出是:

Derived::function
c++ visual-c++
1个回答
0
投票

访问控制适用于名称,而不适用于对象。例如,

class C {
private:
    int value;
public:
    int & getValue() { return value; }
};

您无法访问value这个名称,但您可以访问value通过getValue()引用的对象。

在代码中,

Base * b = new Derived();
b->function();

你正在使用function的名字Base,它是公开的。所以你可以访问它。另一方面,

Derived * d = new Derived();
d->function();

将是一个编译错误,因为您正在使用functionDerived,这是私有的。

© www.soinside.com 2019 - 2024. All rights reserved.