You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现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;
    }
}

代码说明

  1. 字符串匹配逻辑:通过if-else分支判断传入的函数名字符串,匹配成功则调用对应成员函数。
  2. 未知函数处理:当没有匹配到已定义的成员函数名时,输出指定格式的错误提示。

替换后的代码运行后,会完全符合预期输出要求。

内容的提问来源于stack exchange,提问作者nick diaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 00:35:30