c++ - 在 .h 中声明 STL 数据结构,例如 Vector

标签 c++ data-structures vector header-files

我正在尝试在我的 C++ 头文件中声明一个私有(private)数据结构,例如 Vector,我想最终在我的 .cpp 的方法实现中使用它。

一个例子是我的标题“SomeClass.h”,我有:

class SomeClass
{
  private:
  Vector<T> myVector;
  public:
  void AddTtoMyVector(T add);
}

在我的“SomeClass.cpp”.cpp 中,我有以下内容:

#include "SomeClass.h"

SomeClass::AddTtoMyVector(T add)
{
     myVector.Push_back(add);
}

这里的语法行得通吗?或者是否有不同的方式来声明和填充此类结构?

最佳答案

请务必指定您使用的是 STL 的 vector ,使用任一

std::vector<T> myVector;

using std::vector;

此外,如果 T 是泛型类型,您希望将整个类模板化:

#include <vector>

using std::vector;

template< typename T >
class SomeClass
{
  private:
  vector<T> myVector;
  public:
  void AddTtoMyVector(T add) {myVector.push_back( add );}
}

关于c++ - 在 .h 中声明 STL 数据结构,例如 Vector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2525869/

相关文章:

c++ - 什么是安全墙,我该如何使用它?

c++ - 对 2 组不同的数组进行排序

c++ - while 循环没有结束

algorithm - 从层序遍历输出构造一个唯一的二叉搜索树

c++ - 无法将所需数量的元素推送到 vector 中

algorithm - 用适当的设计替换特定顺序的 if/else(基于规则/优先级的 if/else)

javascript - 找到要在括号字符串的开头或结尾添加的最少括号以使其平衡

c++ - 在 C++ 中,我将如何从文本文件中获取特定行并将其存储在 char vector 中?

arrays - 在 R 中向量化 S4 类

c - 使用 NULL 数组将内存分配给二维数组 (c)