簡體   English   中英

如何訪問派生類的私有方法?

[英]How am I able to access derived class private method?

下面的代碼使我可以訪問派生類的私有成員函數。 據我所知,無法通過任何方式訪問班級的私人成員。 下面的代碼如何能夠訪問派生類的私有方法?

#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

訪問控制適用於名稱,而不適用於對象。 例如,

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

您無法訪問名稱value但是可以通過getValue()訪問value引用的對象。

在代碼中

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

您正在使用Base的名稱function ,並且它是公共的。 這樣您就可以訪問它。 另一方面,

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

這將是一個編譯錯誤,因為您使用的是Derived function ,該function是私有的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM