【发布时间】: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 与输入匹配。
可以返回的元素可以是Derived1、Derived2、Derived3中的任何一个,这就是我尝试将其模板化的原因。
但是,在源文件中我收到这些错误提示
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 << foo[x];? 2) 此外,非 void 函数必须在所有代码路径中返回 something。您的运营商没有。因此,在那些不返回任何内容的情况下,它会调用 UB。 -
如果找不到
"TEXT",它会返回什么?脱离例程的末尾将是未定义的行为。应该是throw的东西。 -
getName->getName()?虽然没有足够的信息可以确定。 -
@AlgirdasPreidžius,很抱歉,我不明白您所说的第 1 点)的意思。
标签: c++ class oop templates operator-overloading