C++ 如何重载 [] 运算符并进行函数调用

C++ How to overload the [] operator and make a function call

本文关键字:运算符 函数调用 何重载 重载 C++      更新时间:2023-10-16

抱歉。 我不知道怎么问这个问题,所以我举个例子。

  1. 从命令行获取参数字符串 示例:MyProgram.exe -logs=yes -console=no

    CmdLine CmdLine( ::GetCommandLine() );  // Get arg string.
    
  2. 当我有参数字符串时。 我希望查找"日志"("是"(和"控制台"获取其值 ("否"(。

    CmdLine.GetKey["logs"].GetValue();      // Get the value of "logs".
    CmdLine.GetKey["console"].AsBool();     // Get the value of "console".
    

我必须重载 [] 运算符 (void operator[] ( const std::string & str );(

GetKey["logs"]; // okay.

但我不知道如何或是否可以C++做这样的事情;

CmdLine.GetKey["console"].MyFunction();  // HOW to do this?

我怎样才能告诉"GetKey"调用"MyFunction((。(对不起,措辞不好,但我不知道知道 这叫什么。

感谢您的患者、帮助和想法。

编辑:

很抱歉造成混乱!

CmdLine.GetKey["logs"].GetValue(); // Example!!!
  1. 我重载了 [],所以我可以在 std::map、std::unordered_map(无论如何(中查找"日志"。

  2. 当我找到"logs"时,我希望"GetKey["logs"]"调用"GetValue(("并返回 值。 当我这样做时,我知道这叫什么;

    Func((.SomeFunc((.SomeOtherFunc((;

因为我想做我试图解释的例子。

让我们一步一步地剖析它:

CmdLine.GetKey["logs"].GetValue();
// call method on some object
// call operator [] on GetKey
// GetKey is a member of CmdLine

正如评论中提到的,GetKey对成员来说不是一个好名字。我想你并不真正需要它,但这只是你试图表达你正在查找你想在CmdLine中调用GetValue()的对象。我不得不承认,我不完全理解这个例子。无论如何。。。

您可以operator[]返回一个对象,该对象具有可以调用的成员函数:

#include <iostream>
struct foo {
std::string value;    
void print() { std::cout << value; }
};
struct bar {
foo operator[](const std::string& x) {
return {x};
}
};
int main(int argc, char *argv[])
{
bar b;
b["hello world"].print();
}

输出:

hello world

有关运算符重载的更多信息,请阅读运算符重载的基本规则和习语是什么?。