C++ 基类的虚拟朋友函数?

C++ 基类的虚拟朋友函数?,c++,class,function,virtual,friend,C++,Class,Function,Virtual,Friend,我正在学习这门语言,这是毫无疑问的 是否可以使用虚拟朋友功能?我不知道这是否可能,我甚至没有测试它,但在某些情况下它可能是有用的。例如,对于重载运算符Nope,friendvirtual函数根本没有意义 friend函数不是方法(也称为成员函数),有权访问私有/受保护的类的成员 virtual函数只能是成员函数。您不能有虚拟非成员函数 您可以使操作符虚拟函数不是友元函数。 虚拟函数仅在程序中使用继承时使用,其中一个类作为基类,另一个作为派生类。 虚拟函数用于对象的动态绑定。这意味着您可以将派生

我正在学习这门语言,这是毫无疑问的


是否可以使用虚拟朋友功能?我不知道这是否可能,我甚至没有测试它,但在某些情况下它可能是有用的。例如,对于重载运算符Nope,
friend
virtual
函数根本没有意义

friend
函数不是方法(也称为成员函数),有权访问
私有
/
受保护的
类的成员

virtual
函数只能是成员函数。您不能有
虚拟
非成员函数



您可以使
操作符虚拟函数不是友元函数。
虚拟函数仅在程序中使用继承时使用,其中一个类作为基类,另一个作为派生类。
虚拟函数用于对象的动态绑定。这意味着您可以将派生类的对象存储在基类的指针中,并且仍然可以调用该部分派生类的方法。这个概念被称为

友元函数用于访问类的私有接口。即使在类中没有使用继承,也可以使用它们。

C++中的朋友函数不能声明为虚拟的,因此不可能有朋友函数的动态绑定。如果层次结构中的每个类都需要重载的友元函数,则将友元函数应用于整个类层次结构会变得很尴尬。由于缺乏对动态绑定的支持,很难证明它实际上是类接口的扩展。虚拟朋友函数习惯用法优雅地解决了这个问题

您需要使用虚拟朋友函数习惯用法。gist中所说的是在基址中保留一个虚函数,并让友元函数调用该函数。它将以多态方式调用派生类的函数

直接从链接复制示例

class Base {
  public:
    friend ostream& operator << (ostream& o, const Base& b);
  protected:
    virtual void print(ostream& o) const{ ... }
};
/* make sure to put this function into the header file */
inline std::ostream& operator<< (std::ostream& o, const Base& b){
  b.print(o); // delegate the work to a polymorphic member function.
  return o;
}

class Derived : public Base {
  protected:
    virtual void print(ostream& o) const{ ... }
};
类基{
公众:

friend ostream&operator不能同时是同一类的朋友和虚拟函数。但是,朋友操作符可以从它正在打印的对象调用虚拟函数

ostream& operator<<(ostream& stream, const BaseClass& rbc)
{
    rbc.print_on(stream);
    return stream;
}

ostream&operator您可以在不使用友元函数的情况下,仅使用公共虚拟方法解决此问题:

struct BaseClass {
  virtual void print(std::ostream& os) const;
};

struct DerivedClass {
  virtual void print(std::ostream& os) const;
};

std::ostream& operator<<(std::ostream& os, const BaseClass& obj) {
  obj.print(os);
  return os;
}
struct基类{
虚拟空白打印(std::ostream&os)常数;
};
结构派生类{
虚拟空白打印(std::ostream&os)常数;
};

std::ostream&operator你应该更明确地说明你对虚拟朋友的意思。我的印象是,你的关注实际上与友谊无关,只是与虚拟有一点关系。问题是动态分派是否可以基于对函数的参数而不是隐式的
this
odríguez很抱歉,我会尽量说得更具体一点。谢谢你的回答。所以,在我的例子中,rbc总是要求operator@Kurospidey对不起,我不确定我是否完全理解你的意思。你能看看我的编辑并说它是否回答了你的问题吗。std::ostream&operator和operator不一定非得是friend、 不,它不一定是一个朋友,但将操作符设置为朋友和助手函数设置为私有并不罕见。
class Base {
  public:
    friend ostream& operator << (ostream& o, const Base& b);
  protected:
    virtual void print(ostream& o) const{ ... }
};
/* make sure to put this function into the header file */
inline std::ostream& operator<< (std::ostream& o, const Base& b){
  b.print(o); // delegate the work to a polymorphic member function.
  return o;
}

class Derived : public Base {
  protected:
    virtual void print(ostream& o) const{ ... }
};
ostream& operator<<(ostream& stream, const BaseClass& rbc)
{
    rbc.print_on(stream);
    return stream;
}
struct BaseClass {
  virtual void print(std::ostream& os) const;
};

struct DerivedClass {
  virtual void print(std::ostream& os) const;
};

std::ostream& operator<<(std::ostream& os, const BaseClass& obj) {
  obj.print(os);
  return os;
}