在C++中,如何在不使用友元函数的情况下通过对象调用私有函数?

h4c*_*k3d 5 c++ oop polymorphism dynamic-binding

我遇到了用C++编写的代码:

#include<iostream>
using namespace std;

class Base {
public:
    virtual int fun(int i) { cout << "Base::fun(int i) called"; }
};

class Derived: public Base {
private:
    int fun(int x)   { cout << "Derived::fun(int x) called"; }
};

int main()
{
    Base *ptr = new Derived;
    ptr->fun(10);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:

 Derived::fun(int x) called 
Run Code Online (Sandbox Code Playgroud)

在以下情况中:

#include<iostream>
using namespace std;

class Base {
public:
    virtual int fun(int i) { }
};

class Derived: public Base {
private:
    int fun(int x)   {  }
};
int main()
{
    Derived d;
    d.fun(1);
    return 0;
} 
Run Code Online (Sandbox Code Playgroud)

输出:

Compiler Error.

谁能解释为什么会这样?在第一种情况下,通过对象调用私有函数.

Cod*_*ash 3

第一种情况发生了多态性。它会导致动态或后期绑定。正如第二个答案中提到的,有时它会变得非常危险。

您无法从类定义的外部直接访问类的私有接口。如果您想在不使用友元函数的情况下访问第二个实例中的私有函数,正如问题标题所暗示的那样,请在您的类中创建另一个公共函数。使用该函数来调用这个私有函数。像这样。

 int call_fun (int i) ;
Run Code Online (Sandbox Code Playgroud)

fun()从里面调用。

int call_fun (int i)
{
  return fun (i) ;  //something of this sort, not too good
}
Run Code Online (Sandbox Code Playgroud)

像这样仅用于调用另一个函数的函数称为wrapper functions.

制作friends也不总是可取的。这违背了信息隐藏的原则。