简体   繁体   English

如何与朋友 function 和 inheritance 拆分定义和声明

[英]How to split definition and declaration with friend function and inheritance

I need to compile something like this:我需要编译这样的东西:

struct Base {
    virtual void func1()=0;
    // ...
    friend void Derived::func2(Base *base);
private:
    int some_private;
}

struct Derived : Base {
    virtual func3()=0;
    // ...
    void func2(Base *child) {
        std::cout << child->some_private;
    }
};

But I keep getting compilation error.但我不断收到编译错误。 I tried swapping structures or declaring them first, but I can't declare Derived first (because of inheritance), and I can't declare Base first (because I need to declare friend function in Derived).我尝试交换结构或先声明它们,但我不能先声明 Derived(因为继承),也不能先声明 Base(因为我需要在 Derived 中声明朋友 function)。 What to do?该怎么办?

You have a few basic solutions.你有一些基本的解决方案。 The most obvious is to change from private to protected.最明显的就是从私有变为受保护。 In C++, protected means subclasses have access.在 C++ 中,受保护意味着子类可以访问。

You can add more public (perhaps protected) accessor methods instead.您可以添加更多公共(可能受保护的)访问器方法。

You can forward-reference the entire Derived class and friend the entire class.您可以前向引用整个 Derived class 和整个 class 的朋友。

Personally, I have never felt a need to use friend methods or classes, and I don't know under what circumstances I'd have to be in before I wouldn't depend on other ways to accomplish whatever I'm trying to accomplish.就个人而言,我从来没有觉得需要使用友元方法或类,而且我不知道在什么情况下我必须在我不依赖其他方法来完成我想要完成的任何事情之前。

For this particular solution, I'd change the access to protected.对于这个特定的解决方案,我会将访问权限更改为 protected。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM