【问题标题】:My friend function is not executing我的朋友功能没有执行
【发布时间】:2013-10-12 16:14:43
【问题描述】:

我在我的头文件中声明了一个友元函数,并在我的 .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”。这是作为参数传递给函数的。

【问题讨论】:

    标签: c++ friend-function


    【解决方案1】:

    empPositionyearOfExpsalaryEmployee 类的成员,所以你需要

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

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

    【讨论】:

    • 哇...在标题和 .cpp 之间来回切换之后,我从来没有想过。昨晚我应该注意到的。
    猜你喜欢
    • 2011-09-24
    • 2015-11-24
    • 2011-04-17
    • 2014-09-18
    • 2015-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多