将矢量声明为类成员

Vij*_*jay 2 c++ unix solaris

我在头文件中有简单的类:a.hh

#ifndef a_hh
#define a_hh

class a
{
public: 
    int i;
    a()
    {
        i = 0;
    }

};
#endif
Run Code Online (Sandbox Code Playgroud)

然后我有一个文件:b.cc

#include <iostream> 
#include "a.hh"

using namespace std;

int main(int argc, char** argv)
{

    a obj;
    obj.i = 10;
    cout << obj.i << endl;
    return 0;
}
> 
Run Code Online (Sandbox Code Playgroud)

直到这一点,一切都很好.我编译代码并编译好.但是只要我在课堂上添加一个矢量:

#ifndef a_hh
#define a_hh

class a
{
public: 
    int i;
    vector < int > x;
    a()
    {
        i = 0;
    }

};
#endif
Run Code Online (Sandbox Code Playgroud)

我得到一个编译错误如下:

> CC b.cc
"a.hh", line 7: Error: A class template name was expected instead of vector.
1 Error(s) detected.
Run Code Online (Sandbox Code Playgroud)

将此处的向量声明为成员有什么问题?

hmj*_*mjd 5

您需要#include <vector>并使用限定名称std::vector<int> x;:

#ifndef a_hh
#define a_hh

#include <vector>

class a{
public:
    int i;
    std::vector<int> x;
    a()             // or using initializer list: a() : i(0) {}
    {
        i=0;
    }
};

#endif 
Run Code Online (Sandbox Code Playgroud)

其他要点: