【发布时间】:2015-04-23 18:45:39
【问题描述】:
我是 C++ 新手,正在学习继承和多态。我们需要编写一个包含 4 种员工类型(BasePlusCommission、CommisisonEmployee、Salried 和 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: \n\n";
cout << "Virtual function calls made off base-class pointers:\n\n";
for (const Employee *employeePtr : employees)
virtualViaPointer(employeePtr);
void virtualViaPointer(const Employee * const baseClassPtr)
{
baseClassPtr->print();
cout << "\nEarned $" << baseClassPtr->earnings() << "\n\n";
}
break;
}
}
当我运行项目时,我遇到了这个错误:
错误 C2601:“virtualViaPointer”:本地函数定义为 非法的
void virtualViaPointer(const Employee * const baseClassPtr)
{
baseClassPtr->print();
cout << "\nEarned $" << baseClassPtr->earnings() << "\n\n";
}
谁能帮帮我?非常感谢!
【问题讨论】:
-
这是不言自明的。您在函数 main 中定义了 virtualViaPointer,而在 C++ 中您不能有本地函数(不包括 lambda,但它们有不同的语法)
-
那么我该如何解决这个错误呢?因为我不是很明白你的意思
-
没关系,我想我现在明白了。我解决了。但是谢谢你的想法
标签: c++ pointers inheritance polymorphism