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

C++ [] index operator overloading

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
    }
};

Derived2.h

#pragma once
#include "Derived1.h"
class Derived2 : public Derived1 {
protected:
    int other;

public:
    Derived2() {
        //something
    }
    Derived2(int other) {
        //something
    }
};

Derived3.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];
}
};

Source.cpp

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

我有一个 class Foo,其向量为 Base* class 指针 。 我正在尝试为 Foo 重载 [](索引,下标)运算符,以便我提供一个字符串作为输入,它 returns 来自 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[] 应该是一个只有一个参数的非静态成员函数。模板参数用作 return 类型的模板函数不起作用,因为 foo[x] 的标准调用不允许编译器推断模板类型。

要调用模板化运算符,您需要执行

foo.operator[]<Base>(x)

非常冗长。

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

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

我也修正了你的 return 声明。

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