简体   繁体   English

将向量声明为类成员

[英]declaring a vector as a class member

I have simple class in a header file: a.hh 我在头文件中有一个简单的类: a.hh

#ifndef a_hh
#define a_hh

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

};
#endif

Then i have a file: b.cc 然后我有一个文件: 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;
}
> 

Till this point everything is fine. 到此为止一切都很好。 I compile the code and it compiles fine. 我编译代码,并且编译良好。 But as soon as i add a vector in the class: 但是,一旦我在类中添加向量:

#ifndef a_hh
#define a_hh

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

};
#endif

I get a compilation error as below: 我收到如下编译错误:

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

What is the problem with declaring a vector here as a member? 在此处将向量声明为成员有什么问题?

You need to #include <vector> and use the qualified name std::vector<int> x; 您需要#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 

Other points: 其他要点:

declaring a vector as a class member: 将向量声明为类成员:

#include <iostream>
#include <vector>
using namespace std;

class class_object 
{
    public:
            class_object() : vector_class_member() {};

        void class_object::add_element(int a)
        {   
            vector_class_member.push_back(a);
        }

        void class_object::get_element()
        {
            for(int x=0; x<vector_class_member.size(); x++) 
            {
                cout<<vector_class_member[x]<<" \n";
            };
            cout<<" \n";
        }

        private:
            vector<int> vector_class_member;
            vector<int>::iterator Iter;
};

int main()
{
    class_object class_object_instance;

    class_object_instance.add_element(3);
    class_object_instance.add_element(6);
    class_object_instance.add_element(9);

    class_object_instance.get_element();

    return 0;
}

1.You need to #include <vector> and using namespace std , then a.hh just like below: 1.您需要#include <vector>using namespace std ,然后使用a.hh,如下所示:

#ifndef a_hh
#define a_hh

#include <vector>
using namespace std;

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

};
#endif

2. If you don't want to only use std namespace in all your code, you can specified the namespace before type, just like std::vector<int> x; 2.如果不想只在所有代码中使用std名称空间,则可以在类型之前指定名称空间,就像std::vector<int> x;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM