c++ - 我的 friend 功能没有执行

标签 c++ friend-function

我在我的头文件中声明了一个友元函数,并在我的 .cpp 文件中定义了它,但是当我编译时,我被告知变量“尚未在此范围内声明”。据我了解,当一个函数被标记为类的友元时,该函数能够直接访问该类的所有成员,那么为什么会出现此错误?

我的 .h 文件:

#ifndef EMPLOYEE_H
#define EMPLOYEE_H

#include<string>
using namespace std;

class Employee
{
  friend void SetSalary(Employee& emp2);

 private:

  string name;
  const long officeNo;
  const long empID;
  int deptNo;
  char empPosition;
  int yearOfExp;
  float salary;
  static int totalEmps;
  static int nextEmpID;
  static int nextOfficeNo;

 public:
  Employee();
  ~Employee();
  Employee(string theName, int theDeptNo, char theEmpPosition, int theYearofExp);
  void Print() const;
  void GetInfo();
};

#endif

my.cpp 文件中的函数

void SetSalary(Employee& emp2)
{

  while (empPosition == 'E')
    {
      if (yearOfExp < 2)
        salary = 50000;
      else
        salary = 55000;
    }
}

注意:在我的 Main.cpp 中,我正在创建一个对象“emp2”。这将作为参数传递给函数。

最佳答案

empPositionyearOfExpsalaryEmployee 类的成员,因此您需要

while (emp2.empPosition == 'E') ....
//     ^^^^

对于涉及 yearOfExpsalary 的表达式也是如此。 friend 函数是非成员函数,因此它们只能通过该类的实例(在本例中为 emp2)访问它们是友元的类的数据成员。

关于c++ - 我的 friend 功能没有执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19336430/

相关文章:

c++ - 在私有(private)函数中锁定/解锁互斥锁

c++ - 声明一个模板函数,将模板类 friend 的两个对象(仅)用于这两个特化

c++ - A<T>的 friend 也可以成为A<A<T>>的 friend 吗?

c++ - 限制多个模板参数友元函数可访问的类实例的范围

c++ - friend 功能无法访问私有(private)成员

c++ - Friend 成员函数可以在单独的文件中使用吗?

c++ - 在不使用 vector 的情况下将字符串拆分为 C++ 中的数组

c++ - 为什么符号扩展错误具有很高的安全风险?

c++ - C++ 的拆分函数

c++ - 线程 - 同步和 sleep 线程拒绝唤醒(LINUX)