gpt4 book ai didi

C++ 无用友元函数声明

转载 作者:行者123 更新时间:2023-11-28 02:41:24 25 4
gpt4 key购买 nike

好吧,我声明了一个友元函数,它在:

// user-proc.h
class cregister{
private:
levy user; // typedef struct
int testp;
public:
friend void test();
cregister(levy &tmp);
levy getUser();
void displayUser(levy &);
};

然后我把它定义在:

// user-proc.cpp
void test()
{
cout << "test" << endl;
}

我正在尝试调用 main 函数,但它给了我 It wasn't declared in this scope。我做了一些研究,但我发现,他们说 friend 类型并不完全是声明,你也必须在类外定义它。我试过了,然后通常错误消失了,但碰巧友元函数无法访问私有(private)成员。

编辑:我使用了 void test();在类定义和使用对象之前访问私有(private)成员。它以这种方式修复。

最佳答案

您需要有两个声明:一个是普通的函数原型(prototype)声明,另一个在类中作为友元声明。


// user-proc.h
void test(); // Added prototype

class cregister{
private:
levy user; // typedef struct
int testp;
public:
friend void test(); // Friend declaration still here
cregister(levy &tmp);
levy getUser();
void displayUser(levy &);
};

关于C++ 无用友元函数声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25866082/

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