基类的虚函数函数? [英] Virtual friend functions for a base class?

查看:215
本文介绍了基类的虚函数函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在学习语言的过程中,这是一个noob的疑问。

I'm in the proccess of learning the language and this is a noob doubt.

是否可以使用虚拟好友功能?我不知道是否可能,我甚至没有测试它,但它可能在某些情况下有用。例如,对于重载的运算符<<()。

Is it possible to use a virtual friend function? I don't know if it's possible, I didn't even test it but it could be useful in some situations. For example, for the overloaded operator<<().

DerivedClass dc;
BaseClass &rbc = dc;
cout << rbc;

我的猜测是可能的,但我不确定,因为朋友函数没有在类设计,理论上不是它的一部分(虽然在这个例子中,概念上,有意义的是operator<<()应该是一个方法,但是由于语法限制,不可能实现它作为一个)。

My guess is it's possible, but I'm not sure since a friend function is not implemented in the class design, and theoretically is not part of it (though in this example, conceptually it makes sense that operator<<() should be a method, but due to syntax limitations it's not possible to implement it as one).

编辑:我关心的是这个例子:

my concern is related with this example:

BaseClass bc;
DerivedClass dc;
BaseClass *pArr[2];
pArr[1] = bc;
pArr[2] = dc;
for (int i = 0; i < 2; i++)
    cout << pArr[i];

在这个混合对象数组中,我想要为每个对象调用正确的运算符<< 。

in this array of mixed objects, I want the correct operator<<() called for each one.

推荐答案

不,朋友 / code>函数是没有意义的。

Nope, friend virtual functions doesn't make sense at all.

不是方法(aka成员函数),并且有权访问的成员 private / protected > class

friend functions are such, that are not methods (a.k.a. member functions) and have the right to access private/protected members of a class.

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

virtual functions can only be member functions. You can't have virtual non-member function.

您可以使运算符<< 引用一个基类,然后调用某些 virtual 成员函数。这样,你可以使运算符<< <几乎虚拟:)

You can make the operator<< take a reference to a base class and then call some virtual member function. This way, you can make the operator<< "almost virtual" :)

例如

class A
{
public:
    virtual void f() const { std::cout << "base"; }
};
class B: public A
{
public:
    virtual void f() const { std::cout << "derived"; }
};

std::ostream& operator<<(std::ostream& os, const A& a )
{
     a.f();
     return os;
}

int main()
{
    B b;
    std::cout << b << std::endl;

    return 0;
}

将打印

will print derived.

这篇关于基类的虚函数函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆