如何实现CallFunctionNamed函数以调用LabPrinter类指定成员函数
实现CallFunctionNamed函数,根据函数名字符串调用LabPrinter成员函数
问题背景
已完成课堂编程作业的步骤1并移除相关代码,现在需要实现CallFunctionNamed函数:该函数接收LabPrinter对象引用和函数名字符串,根据字符串调用LabPrinter类对应的成员函数,最终输出要求如下:
2 + 2 = 4 Unknown function: PrintPlus2 Secret string: "abc"
相关代码
LabPrinter.h
#ifndef LABPRINTER_H #define LABPRINTER_H #include <iostream> #include <string> class LabPrinter { protected: const std::string secret; public: LabPrinter(std::string secretStringValue) : secret(secretStringValue) { } virtual void Print2Plus2() { using namespace std; cout << "2 + 2 = 4" << endl; } virtual void PrintSecret() { using namespace std; cout << "Secret string: \"" << secret << "\"" << endl; } };
main.cpp
#include <iostream> #include <string> #include "LabPrinter.h" using namespace std; void CallFunctionNamed(LabPrinter& printer, string functionName) { // Only implement this function after completing step 1 } int main (int argc, char *argv[]) { LabPrinter printer("abc"); // Step 1代码已移除 CallFunctionNamed(printer, "Print2Plus2"); CallFunctionNamed(printer, "PrintPlus2"); CallFunctionNamed(printer, "PrintSecret"); return 0; }
解决方案
由于C++没有原生反射机制,我们可以通过字符串匹配手动映射函数名字符串到对应的成员函数调用。修改CallFunctionNamed函数如下:
void CallFunctionNamed(LabPrinter& printer, string functionName) { if (functionName == "Print2Plus2") { printer.Print2Plus2(); } else if (functionName == "PrintSecret") { printer.PrintSecret(); } else { cout << "Unknown function: " << functionName << endl; } }
代码说明
- 字符串匹配逻辑:通过
if-else分支判断传入的函数名字符串,匹配成功则调用对应成员函数。 - 未知函数处理:当没有匹配到已定义的成员函数名时,输出指定格式的错误提示。
替换后的代码运行后,会完全符合预期输出要求。
内容的提问来源于stack exchange,提问作者nick diaz
相关产品推荐
相关产品推荐

