gpt4 book ai didi

c++ - 继承自 std::vector

转载 作者:行者123 更新时间:2023-11-28 02:36:19 26 4
gpt4 key购买 nike

我目前正在创建一个必须从 std::vector 派生的类。我意识到这样做可能不好,但我必须这样做。现在我的问题是如何访问成员函数中创建的 vector ,基本上使类像访问常规整数 vector 一样访问自身?例如,我正在寻找 myVector.at(0) 的等效项以返回 vector 中的第一项。此外, vector 的大小应始终为 6。这是我目前的代码:

class aHistogram : public vector<int>
{
public:
aHistogram(); //default constructor for histogram class
void update(int face); //Function to update histogram
void display(int maxLengthOfLine); //Displays histogram to the scale of maxLengthOfLine using x's
void clear();//Function to clear histogram bin counts
int count(int face) const; // Function to return number of times a face has appeared
private:
int numx, m, j; //Variables used in functions
};

#endif

下面是需要类访问自身的函数,我知道没有名为“myVector”的 vector ,但我不知道的是能够执行该操作的等效语法。

void aHistogram::clear() 
{
//Clears bin counts to 0
myVector.at(0) = 0;
myVector.at(1) = 0;
myVector.at(2) = 0;
myVector.at(3) = 0;
myVector.at(4) = 0;
myVector.at(5) = 0;
}

最佳答案

如果相关函数没有在派生类中被覆盖,你可以直接调用它:

void HistoGram::clear()
{
at( 0 ) = 0;
// ...
}

运算符也是如此,但您必须使用 (*this)作为左手运算符:

void HistoGram::clear()
{
(*this)[0] = 0;
// ...
}

如果函数或运算符被覆盖,您要么必须限定函数名称,

void HistoGram::clear()
{
std::vector<int>::at( 0 ) = 0;
// ...
}

或将 this 指针转换为基类类型:

void HistoGram::clear()
{
(*static_cast<std::vector<int>*>( this ))[0] = 0;
// ...
}

但是你确定要在这里进行公共(public)继承吗?你说 vector 的大小应始终为 6。你不可能保证使用公共(public)继承;至少,你需要私有(private)继承,然后using声明你的操作想支持。 (我有几个案例需要限制 std::vector像这样,我已经使用 private 实现了遗产。有时转发功能,例如我只想公开 const函数的版本。)

另外:在极少数情况下 std::vector<>::at是合适的。你确定你不想[] , 边界检查您将获得大多数现代实现。

关于c++ - 继承自 std::vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27319433/

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