错误 C2601:"Name":本地函数定义是非法的

error C2601: "Name": local function definitions are illegal

本文关键字:定义 非法 函数 C2601 Name 错误      更新时间:2023-10-16

我是C++新手,学习继承和多态性。我们需要编写一个有4种类型的员工(BasePlusCommission,CommisisonEmployee,Salaried和TipWorker)的员工项目。我的项目有一个 main() 类,我对每种类型的员工都使用了 switch 方法。我被困在TipWorker 上,我们必须做多态性。到目前为止,我得到了什么。

int main()
{
void virtualViaPointer(const Employee * const);
    {
                cout << "Enter First Name: " << endl;
                cin >> firstName;
                cout << "Enter Last Name: " << endl;
                cin >> lastName;
                cout << "Enter SSN: " << endl;
                cin >> SSN;
                if (SSN.length() == 9)
                {
                    SSN = true;
                }
                else
                {
                    cout << "Please enter SSN again with 9 digits only:" << endl;
                    cin >> SSN;
                }
                cout << "Enter wages: " << endl;
                cin >> wage;
                cout << "Enter hours: " << endl;
                cin >> hours;
                cout << "Enter tips: " << endl;
                cin >> tips;
                TipWorker employee4(firstName, lastName, SSN, wage, hours, tips);
                employee4.print();
                cout << fixed << setprecision(2);
                vector < Employee * > employees(1);
                employees[0] = &employee4;
                cout << "Employee processed polymorphically via dynamic binding: nn";
                cout << "Virtual function calls made off base-class pointers:nn";
                for (const Employee *employeePtr : employees)
                    virtualViaPointer(employeePtr);
                void virtualViaPointer(const Employee * const baseClassPtr)
                {
                    baseClassPtr->print();
                    cout << "nEarned $" << baseClassPtr->earnings() << "nn";
                }
                    break;
      }
}

当我运行该项目时,我出现了这个错误:

错误 C2601:"虚拟ViaPointer":本地函数定义为 非法

void virtualViaPointer(const Employee * const baseClassPtr)
                    {
                        baseClassPtr->print();
                        cout << "nEarned $" << baseClassPtr->earnings() << "nn";
                    }

谁能帮我?非常感谢!

您不能在另一个函数中定义一个函数。任何函数定义都应在任何其他函数定义之外。

virtualViaPointer的定义放在main体之外。

您可以在函数内声明函数,但不能定义(!)。但是,您可以在函数中使用本地结构/类或 lambda:

#include <iostream>
void f()
{
  void print(); // mostly useless - maybe a most vexing parse error
  struct Print {
    static void apply(const char* s) { std::cout << s << 'n'; }
  }
  Print::apply("Hello");
  auto lambda = [] (const char* s) { std::cout << s << 'n'; };
  lambda("World");
}

注意:本地结构不需要 C++11(此外,调试时可能看起来更好)