C++ C++;[]索引运算符重载 Base.h 嘲笑的1 衍生2.h 衍生的3.h 福安
C++ C++;[]索引运算符重载 Base.h 嘲笑的1 衍生2.h 衍生的3.h 福安,c++,class,oop,templates,operator-overloading,C++,Class,Oop,Templates,Operator Overloading,运算符[]应该是一个只有一个参数的非静态成员函数。模板参数用作返回类型的模板函数不起作用,因为foo[x]的标准调用不允许编译器推断模板类型 要调用模板化操作符,需要执行以下操作 foo.operator[]<Base>(x) 我还修正了你的回报声明 请注意,可以对您的运算符[]进行其他改进,并且您不会处理在向量中找不到下标值的情况(您将尝试引用Vect[-1],这将是未定义的行为)。1)您希望t推断出什么结果,在callstd::cout中,如果找不到“TEXT”,它将返回什么?
运算符[]
应该是一个只有一个参数的非静态成员函数。模板参数用作返回类型的模板函数不起作用,因为foo[x]
的标准调用不允许编译器推断模板类型
要调用模板化操作符,需要执行以下操作
foo.operator[]<Base>(x)
我还修正了你的回报声明
请注意,可以对您的
运算符[]
进行其他改进,并且您不会处理在向量中找不到下标值的情况(您将尝试引用Vect[-1]
,这将是未定义的行为)。1)您希望t
推断出什么结果,在callstd::cout中,如果找不到“TEXT”
,它将返回什么?从例行程序的末尾掉下来将是未定义的行为。可能应该抛出一些东西。getName
->getName()
?虽然没有足够的信息可以确定。@AlgirdasPreidžius,很抱歉我不明白你说的第一点的意思)。是的,我想我必须删除模板内容。根据操作员[]
的改进,我知道。它仍然是一个WIP,不是最终的特性,但我真的想在继续之前解决这些问题。非常感谢。
#pragma once
#include "Base.h"
class Derived1 : public Base {
protected:
int other;
public:
Derived1() {
//something
}
Derived1(int other) {
//something
}
};
#pragma once
#include "Derived1.h"
class Derived2 : public Derived1 {
protected:
int other;
public:
Derived2() {
//something
}
Derived2(int other) {
//something
}
};
#pragma once
#include "Derived2.h"
class Derived3 : public Derived2 {
protected:
int other;
public:
Derived3() {
//something
}
Derived3(int other) {
//something
}
};
#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];
}
};
Foo foo;
std::string x = "TEXT";
std::cout << foo[x];
foo.operator[]<Base>(x)
Base& operator[](std::string name)
{
// ...
return *Vect[index]
}