【问题标题】:C++ [] index operator overloadingC++ [] 索引运算符重载
【发布时间】:2021-08-01 01:21:50
【问题描述】:

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 pointers。 我正在尝试为Foo 重载[](索引,下标)运算符,以便我提供一个字符串作为输入,它从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

【问题讨论】:

  • 1) 你期望T 被推导出来,调用std::cout &lt;&lt; foo[x];? 2) 此外,非 void 函数必须在所有代码路径中返回 something。您的运营商没有。因此,在那些不返回任何内容的情况下,它会调用 UB。
  • 如果找不到"TEXT",它会返回什么?脱离例程的末尾将是未定义的行为。应该是throw 的东西。
  • getName -> getName()?虽然没有足够的信息可以确定。
  • @AlgirdasPreidžius,很抱歉,我不明白您所说的第 1 点)的意思。

标签: c++ class oop templates operator-overloading


【解决方案1】:

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

要调用您的模板化运算符,您需要这样做

foo.operator[]<Base>(x)

非常冗长。

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

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

我还修正了你的退货声明。

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

【讨论】:

  • 是的,我认为我必须删除模板内容。根据operator[] 的改进,我知道。它仍然是一个 WIP,而不是最终功能,但我真的想在更进一步之前解决问题。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-22
  • 2023-03-29
  • 2016-02-19
相关资源
最近更新 更多