gpt4 book ai didi

c++ - 为什么它的 friend 无法访问这个私有(private)构造函数

转载 作者:搜寻专家 更新时间:2023-10-31 01:48:42 24 4
gpt4 key购买 nike

#include <iostream>

using namespace std;


class B {
private:
class A;
friend void f ( A Aobj );
B ( int i ) {}
};

class A{
};


void f ( A Aobj ) {
B Bobj ( 1 );
}

int main() {
}

g++ 产生以下错误:

$ g++ a.cpp
a.cpp: In function ‘void f(A)’:
a.cpp:10: error: ‘B::B(int)’ is private
a.cpp:18: error: within this context

如果进行以下任何更改,错误就会消失:1. 从 B 的构造函数中删除“int i”。2. 将 f 的数据类型从 A 更改为任何其他类型:例如 void f (int Aobj)。3. 在B之前定义类A,去掉A的前向声明。

最佳答案

问题是 friend 函数采用 B::A,而文件后面的函数采用 A。将 class A 的前向声明移出 B

关于c++ - 为什么它的 friend 无法访问这个私有(private)构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17432205/

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