C++ - 错误 - 没有运算符"[]"与这些操作数匹配

C++ - Error - No operator "[]" matches these operands

本文关键字:操作数 错误 运算符 C++      更新时间:2023-10-16

我正在为一个容器编写代码,该容器存储字符串并按字母顺序对其进行排序(认为这将是一个有趣的想法)。我一直在尝试放置一个"[]"运算符并将其分配给私有成员单词,以便我可以访问该成员内部的任何数据或字符串。但是,我一直在努力解决这个无法修复的连续错误。它说:

No operator "[]" matches these operands. Operand types are std::shared_ptr<std::vector<std::string, std::allocator<std::string>>>[size_t]

以下是有关错误的一些代码(错误存在于类.cpp):

类.h

#pragma once
#include <memory>
#include <vector>
#include <string>
#include <iostream>

class sort
{
public:
//...

sort(int i): words(std::make_shared<std::vector<std::string>>(i)) { } 
std::shared_ptr<std::vector<std::string>> & operator [](size_t st);
//...
private:
std::shared_ptr<std::vector<std::string>> words;
std::string alpha = "abcdefghijklmnopqrstuvwxyz";
};

类.cpp

#include "sort.h"
#include <memory>
#include <vector>
#include <iostream>
//...
std::shared_ptr<std::vector<std::string>> & sort::operator[](size_t st) 
{
return words[st]; //Error is defined at the brackets
}
//...

另一件需要注意的事情是,如果我删除带有st的括号,错误就消失了(显然不是我想要实现的目标)。对此代码的任何帮助或修复将不胜感激。

您的words成员不是数组或容器。 这是一个std::shared_ptr,在 C++17 之前没有定义operator[](即使这样,您的代码仍然会错误地使用它)。这就是您的operator[]无法编译的原因。

您有一个指向存储在内存1中其他位置的std::vector<std::string>对象的std::shared_ptr。 如果你想让你的operator[]访问该std::vector中的std::string值,你需要先尊重指针才能访问std::vector,然后你可以调用它的operator[]。 您需要将operator[]的返回值固定为单个std::string,而不是std::shared_ptr

1:你为什么要使用指针?为什么不直接在类中将words声明为实际的std::vector对象?std::vector<std::string> words;

试试这个:

类.h

#pragma once
#include <memory>
#include <vector>
#include <string>
#include <iostream>
class sort
{
public:
//...
std::string& operator [](size_t st);
//...
private:
std::shared_ptr<std::vector<std::string>> words;
std::string alpha = "abcdefghijklmnopqrstuvwxyz";
};

类.cpp

#include "sort.h"
#include <memory>
#include <vector>
#include <iostream>
//...
std::string& sort::operator[](size_t st) 
{
return (*words)[st];
}
//...

问题可能是words是一个std::shared_ptr,而不是一个std::vectorstd::shared_ptr::operator[]()是 C++17 的东西(意味着它不会在 C++11 中编译),即使这样,它也不会做你认为它做的事情:

返回值

对数组的第 idx-th 元素的引用,即 get()[idx]

然后,从get()的文档中:

std::shared_ptr::get

T* get() const noexcept;(至C++17)

element_type* get() const noexcept;(自C++17起)

这意味着get()返回一个指针。总之,这有效地使您的代码与以下代码相同:

std::vector<int>* ptr = nullptr; // Note that this data is probably  allocated some how...
// Then, later...
ptr[index];

那不是你想要的。这基本上等同于访问向量数组的第index个元素(它比这更复杂,但我对指针和数组之间的技术差异了解不够,无法在这里正确表达它)。你想要的是取消引用指针的operator[](),如下所示:

(*ptr)[index]; // Parenthesis for clarity. I don't think that they are technically necessary here.

这归结为:你(可能)想要的是std::shared_ptr的取消引用运算符:

return (*words)[st]; // again, parenthesis for clarity here.
// I don't think they are technically necessary here, either.

这应该编译并做你想做的事。

编辑:由于Remy Lebeau的回答,我注意到您的函数原型也需要更改,因为(*words)[st]不是std::shared_ptr<std::vector<std::string>>,它只是std::string。因此,将原型更改为以下内容:

std::string& operator [](size_t st);

在 CPP 中:

std::string& sort::operator[](size_t st) 
{
return (*words)[st];
}