gpt4 book ai didi

c++ - C++ 中的 friend 成员函数 - 前向声明不起作用

转载 作者:行者123 更新时间:2023-11-28 07:05:20 25 4
gpt4 key购买 nike

我遇到的情况与 Specify a class member function as a friend of another class? 中描述的情况类似.

但是在我的例子中,B 类需要知道 A 类,因为它正在使用它,所以该线程中给出的解决方案对我不起作用。我也试图对函数本身进行前向声明,但效果不佳。似乎每个类都需要另一个类的完整定义......

有什么简单的方法可以解决吗?我更喜欢一种不涉及包装旧类之一的新类的解决方案。

代码示例:

//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(); }
};

感谢各位 helper !

(顺便说一句,这是我的第一个问题,希望我能解释清楚)

最佳答案

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

//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++ - C++ 中的 friend 成员函数 - 前向声明不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21850292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com