我是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: \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";
}
任何人都可以帮助我吗?非常感谢你!
答案 0 :(得分:2)
您可能无法在其他功能中定义一个功能。任何函数定义都应该在任何其他函数定义之外。
将main
的定义放在var buffer = {};
messageSource.on('message', function (msg) {
var msgKeys = Object.keys(msg); // Get the list of IDs
msgKeys.forEach(function (key) { // For each numeric key...
buffer[key] = msg[key]; // Copy the message
});
});
的正文之外。
答案 1 :(得分:0)
您可以在函数内部声明函数,但不能定义该函数的定义(!)。但是,您可以在函数中使用本地结构/类或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(另外,调试时可能看起来更好)