C ++中的朋友成员函数-前向声明不起作用 [英] friend member function in C++ - forward declaration not working

查看:111
本文介绍了C ++中的朋友成员函数-前向声明不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到的情况与但是,在我的情况下,由于类B正在使用它,因此它需要知道它,因此该线程中给出的解决方案对我来说不起作用.我试图也给函数本身做一个前向声明,但效果不佳.似乎每个类都需要另一个的完整定义...

However in my case, class B needs to know class A since it's using it, so the solution given in that thread is not working for me. I tried to give also a forward declaration to the function itself but it didn't work as well. It seems that each class need the full definition of the other...

有没有简单的方法可以解决?我更喜欢一个不包含封装旧类的新类的解决方案.

Is there any easy way to solve it? I prefer a solution which doesn't involve new classes which wrap one of the old classes.

代码示例:

//A.h
class B; //not helping
void B::fB(); //not helping

class A
{
public:
    friend void B::fB();
    void fA(){};
protected:
    void fA_protected(){};
};

//B.h
#include "A.h"

class B
{
private:
    A a;

public:
    void fB(){ a.fA_protected();} // this function should call the protected function
    void fB2(){ a.fA(); } 
};

感谢帮手!

(通过这是我的第一个问题,希望我能清楚地说明自己)

(By the way this my first question, I hope I explain myself clearly)

推荐答案

如果可以更改B以在A上获取指针,则可能会有所帮助: (我使用原始指针,因为根据评论您不能使用智能指针.)

If you can change B to take a pointer on A, following may help: (I use raw pointer as you can't use smart pointer according to comment).

//A.h
#include "B.h"

class A
{
public:
    friend void B::fB();
    void fA() {};
protected:
    void fA_protected(){};
};

//B.h
class A; // forward declaration

class B
{
private:
    A* a;

public:
    B();
    ~B();                       // rule of 3
    B(const B& b);              // rule of 3
    B& operator = (const B&);   // rule of 3

    void fB(); // this function should call the protected function
    void fB2(); 
};

//B.cpp

#include "B.h"
#include "A.h"

B::B() : a(new A) {}
B::~B() { delete a; }                      // rule of 3
B::B(const B& b) : a(new A(*b.a)) {}       // rule of 3
B& B::operator = (const B&) { *a = *b.a; return *this; } // rule of 3

void B::fB() { a->fA_protected();}
void B::fB2() { a->fA(); } 

这篇关于C ++中的朋友成员函数-前向声明不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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