C++ 如何重载 [] 运算符并进行函数调用
C++ How to overload the [] operator and make a function call
抱歉。 我不知道怎么问这个问题,所以我举个例子。
从命令行获取参数字符串 示例:MyProgram.exe -logs=yes -console=no
CmdLine CmdLine( ::GetCommandLine() ); // Get arg string.
当我有参数字符串时。 我希望查找"日志"("是"(和"控制台"获取其值 ("否"(。
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!!!
我重载了 [],所以我可以在 std::map、std::unordered_map(无论如何(中查找"日志"。
当我找到"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
有关运算符重载的更多信息,请阅读运算符重载的基本规则和习语是什么?。
相关文章:
- C++ 如何重载 [] 运算符并进行函数调用
- 在 C++ 中调用类中的运算符函数
- NOEXCEPT 函数调用运算符的说明符_Not_fn
- 检查类是否具有可能重载的函数调用运算符
- C++函数调用与许多点运算符
- C++ 类的构造函数和函数调用运算符 () 重载之间的歧义
- 重载运算符主体仅包含一个函数调用
- 重载<<运算符的函数调用 (C++)
- 使用赋值运算符将宏转换为函数调用
- 为什么将"<<"运算符作为函数调用会导致"ambiguous call"编译器错误?
- 如何调用运算符函数添加两个对象?
- 将函数调用替换为重载运算符 C++
- 在呼叫运算符函数const中调用运算符时错误
- 运算符 () 括号是否会在函数调用中创建的对象上调用
- 当您可以使用构造函数时,为什么要重载 C++ 类或结构中的 () 运算符(可调用运算符)
- 重载时获取堆栈溢出 >> 运算符函数是为类调用的。我需要进行哪些更改?
- 内置运算符(新的,删除和函数调用除外)如何返回
- 为下标运算符和函数调用运算符提供默认参数
- 使用重载运算符在函数调用时执行操作
- 流输出和隐式void*cast运算符函数调用