gpt4 book ai didi

c++ - operator [] 在 vector 类上重载

转载 作者:行者123 更新时间:2023-11-30 05:03:18 25 4
gpt4 key购买 nike

我正在尝试重载 [] 运算符,以便当程序员希望检索和设置字符串的特定字符时,该字符串包含在 vector 的一个点中,传递给 [] 的数字将引用来自的第 i 个字符 vector 的开头,到结尾。

例如:这是一个 vector 。从头(0)开始,内容如下:

dog
cat
parrot

其中“dog”是 vector 中的第一个字符串,“parrot”是最后一个。我希望 [] 运算符按如下方式运行:

searchable_vector vec;
vec.push_back("dog");
vec.push_back("cat");
vec.push_back("parrot");

std::cout << vec[3] << " should say 'c' ";

这是我的 searchable_vector.hpp:

#pragma once
#include <vector>
class searchable_vector : public std::vector<std::string>
{
public:
char& operator [] (int n);
private:
std::vector<std::string> vector;
};

这是 searchable_vector.cpp:

char& searchable_vector::operator[] (int i)
{
// 'for each' string in vector member, count
// the length and add it to a counter until
// the counter is at desired 'length' (given from i)
unsigned int counter = 0;
unsigned int spot_in_string = 0;
std::string holding_string = "";

std::vector<std::string>::iterator it;
it = vector.begin();

while (it != vector.end() && counter != i)
{
if (counter == i) // it is where it needs to be
break;
else
{
spot_in_string = it->length() - 1;
if (counter != 0)
counter += spot_in_string + 1;
else
counter += spot_in_string;

if (counter < i) // look in next string
{
it++;
}
else if (counter > i)
{
while (counter != i) // go 'back' one at a time
{
counter--;
spot_in_string--;
}
break; //should break out of master while loop
}
}
}
holding_string = *it;
return holding_string[spot_in_string];
}

我不会太担心这段代码内部的逻辑,但我认为我在重载方面做得不对,因为我在测试中遇到了 Linker 2019 错误(使用 Visual Studio)单元测试文件:

TEST_CASE("Test searchable_vector class [] operator", "[searchable_vector]")
{
searchable_vector vec;
vec.push_back("dog");
vec.push_back("cat");
vec.push_back("parrot");
char result = vec[3];
REQUIRE(result == 'c');
}

错误如下:

LNK2019 unresolved external symbol "public: char & __cdecl 
searchable_vector::operator[](int)" (??Asearchable_vector@@QEAAAEADH@Z)
referenced in function "void __cdecl ____C_A_T_C_H____T_E_S_T____2(void)" (?
____C_A_T_C_H____T_E_S_T____2@@YAXXZ) unit_tests

接着是我的 VM_Module.obj 所在的目录

我认为这只是我重载的一些基本问题,而不是逻辑本身。如果那被打破,它应该仍然链接并运行,只是表现不佳或崩溃。

我们将不胜感激任何建设性的反馈。

此外,我想重载它的原因是,我将要编写的代码期望 searchable_vector 对象的行为如前所述,返回 vector 中的第 i 个字符,如果成功实现,应该是干净和容易的来写。谢谢。

最佳答案

链接的问题是因为我没有将标题和源代码添加到我的 CMakelists.txt 中,我想 CMake 无法“了解”。更改后,我重新运行 cmake,一切正常。

至于从 vector 继承的危险,是的,当我发现我的私有(private) vector 中没有任何内容时,我就知道了。这是因为当我调用

vec.push_back("somestring");

在我的测试中,push_back()(继承自 vector)将值存储到 INHERITED“集合”(如果您愿意),而不是我的私有(private)集合。所以我只是删除了我的私有(private) vector ,因为它是不必要的,并且稍微改变了我的 cpp,所以它被设置为

it = this->begin();

而不是

it = vector.begin();

所以它现在可以工作了:)

关于c++ - operator [] 在 vector 类上重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49480335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com