C++[]索引运算符重载



Base.h

#pragma once
class Base {
protected:
std::string name;
public:
Base() {
//something
}
Base(std::string name) {
//something
}
std::string getName() {
return this->name;
}
void setName(std::string name) {
this->name = name;
}
};

衍生1

#pragma once
#include "Base.h"
class Derived1 : public Base {
protected:
int other;
public:
Derived1() {
//something
}
Derived1(int other) {
//something
}
};

衍生2.h

#pragma once
#include "Derived1.h"
class Derived2 : public Derived1 {
protected:
int other;
public:
Derived2() {
//something
}
Derived2(int other) {
//something
}
};

衍生3.h

#pragma once
#include "Derived2.h"
class Derived3 : public Derived2 {
protected:
int other;
public:
Derived3() {
//something
}
Derived3(int other) {
//something
}
};

Foo.h

#include <vector>
#include <string>
#include "Base.h"
#include "Derived1.h"
#include "Derived2.h"
#include "Derived3.h"
class Foo {
private:
std::vector<Base*> Vect;
public:
Foo() {
//something
}
template<typename T>
T& operator[](std::string name) {
bool found = false;
int index = -1;
for (int i = 0; i < Vect.size(); i++) {
if (Vect[i]->getName() == name) {
found = true;
index = i;
}
if (found == true) {
break;
}
}
return Vect[index];
}
};

来源.cpp

Foo foo;
std::string x = "TEXT";
std::cout << foo[x];

我有一个类Foo,其向量为Base*类别指针。我试图重载Foo[](index,subscript(运算符,这样我就给出了一个字符串作为输入,它从Vect返回一个元素,其私有成员name与输入匹配。可以返回的元素可以是Derived1Derived2Derived3中的任何一个,这就是我尝试将其模板化的原因。

然而,在源文件中,我得到了这些错误,说

no operator "[]" matches these operands
operand types are: Foo[std::string]
Foo does not define this operator or a conversion to a type acceptable to the predefined operator

operator[]应该是一个只有一个参数的非静态成员函数。将模板参数用作返回类型的模板函数不起作用,因为foo[x]的标准调用不允许编译器推断模板类型。

要调用模板化操作符,您需要执行

foo.operator[]<Base>(x)

这是非常冗长的。

删除模板内容并将运算符的返回类型更改为Base &

Base& operator[](std::string name)
{
// ...
return *Vect[index]
}

我还修正了你的报税表。

请注意,还可以对operator[]进行其他改进,并且您不处理在向量中找不到下标值的情况(您将尝试引用Vect[-1],这将是未定义的行为(。

最新更新