通过 [ " " ] 或 [int] 为自定义类C++访问组件
C++ access component via [""] or [int] for custom class
我注意到C++中的以下内容。
SomeClass obj = SomeClass();
int boo = obj["foo"];
这叫什么?我该怎么做?
示例
class Boo {
public:
int GetValue (string item) {
switch (item) {
case "foo" : return 1;
case "apple" : return 2;
}
return 0;
}
}
Boo boo = Boo();
int foo = boo.GetValue("foo");
// instead of that I want to be able to do
int foo = boo["foo"];
要使用[]
,您需要重载operator[]
:
class Boo {
public:
int operator[](string const &item) {
if (item == "foo")
return 1;
if (item == "apple")
return 2;
return 0;
}
};
你可能有兴趣知道std::map
已经提供了你想要的东西:
std::map<std::string, int> boo;
boo["foo"] = 1;
boo["apple"] = 2;
int foo = boo["foo"];
明显的区别在于,当/如果您使用它来查找以前未插入的值时,它将插入一个具有该键和值0的新项。
这被称为运算符重载。您需要定义操作员[]
的工作方式:
#include <string>
class Boo {
public:
int operator[] (std::string item) {
if (item == "foo") return 1;
else if (item == "apple") return 2;
return 0;
}
};
Boo boo = Boo();
int foo = boo["foo"];
另外,开关变量必须是整型,所以我改为if-else。
您需要重载[]运算符。这里有一个例子(奇怪的是,在Java网站上)。
您想要的是重载下标运算符(operator[]
);在你的情况下,你会做:
class Boo {
public:
int operator[](const string & item) const {
// you can't use switch with non-integral types
if(item=="foo")
return 1;
else if(item=="apple")
return 2;
else
return 0;
}
}
Boo boo = Boo();
int foo = boo["foo"];
通常,封装容器的类通过引用返回数据,以允许调用方修改存储的数据;这就是大多数提供operator[]
的STL容器所做的。
相关文章:
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- 用于访问容器<T>数据成员的正确 API
- 访问者访问变体并返回不同类型时出错
- 尝试通过多个向量访问变量时,向量下标超出范围
- 无法访问嵌套类.类的使用无效
- 写入位置0x0000000C时发生访问冲突
- 我们可以访问一个不存在的联盟的成员吗
- C++从另一个类访问公共静态向量的正确方法是什么
- 我的简单if-else语句是如何无法访问的代码
- 从C++dll访问C#中的一行主要参数
- 概念TS检查忽略私有访问修饰符
- 访问被拒绝后,c++中的故障保护代码
- 在c++中访问int到类对象的映射时出错
- 我想访问std::unique_ptr中的一个特定元素
- 为什么示例代码访问IUnknown中已删除的内存
- C++:无法访问声明的受保护成员
- 通过指向指针数组的指针访问子类的属性
- 如何使用单独文件中的派生类访问友元函数对象