【问题标题】:How to avoid access errors while using friend functions in c++?在 C++ 中使用友元函数时如何避免访问错误?
【发布时间】:2020-08-01 11:58:47
【问题描述】:
#include <iostream>
using namespace std;

class boss{
int salary;

public:
 boss();
 boss(int b){
  salary = b;
 }
 friend void total(boss, employe);
};


class employe{
 int salary;
 friend void total(boss, employe);

public:
 employe();
 employe(int e){
  salary = e;
 }
 friend void total(boss, employe);
};

void total(boss b, employe e){
 int T;
 T = b.salary + e.salary;
 cout << T;
}


int main(){

boss bb(200);
 employe ee(300);

 total(bb,ee);
 }

我面临的错误

        16:31:40 **** Incremental Build of configuration Debug for project Practice ****
make all 
'Building file: ../src/Practice.cpp'
'Invoking: Cross G++ Compiler'
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/Practice.d" -MT"src/Practice.o" -o "src/Practice.o" "../src/Practice.cpp"
../src/Practice.cpp:20:26: error: 'employe' has not been declared
   20 |  friend void total(boss, employe);
      |                          ^~~~~~~
../src/Practice.cpp: In function 'void total(boss, employe)':
../src/Practice.cpp:38:8: error: 'int boss::salary' is private within this context
   38 |  T = b.salary + e.salary;
      |        ^~~~~~
../src/Practice.cpp:13:6: note: declared private here
   13 |  int salary = 3000;
      |      ^~~~~~
make: *** [src/subdir.mk:20: src/Practice.o] Error 1
"make all" terminated with exit code 2. Build might be incomplete.

16:31:40 Build Failed. 3 errors, 0 warnings. (took 655ms)

【问题讨论】:

  • 你需要一个雇员类的前向声明。

标签: c++ friend access-specifier


【解决方案1】:

boss 中的 friend total(boss, employe) 声明失败,因为尚未声明 employe

boss上方添加employe的前向声明。

class employe; // <--- add this

class boss{
int salary = 3000;

public:
 boss();
 boss(int b){
  salary = b;
 }
 friend void total(boss, employe);
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-26
    • 2012-03-08
    • 2014-04-02
    • 1970-01-01
    • 1970-01-01
    • 2012-03-19
    • 1970-01-01
    • 2022-10-04
    相关资源
    最近更新 更多