Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declaring a vector as a class member

Tags:

c++

unix

solaris

I have simple class in a header file: a.hh

#ifndef a_hh
#define a_hh

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

};
#endif

Then i have a file: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?

like image 734
Vijay Avatar asked Dec 04 '25 13:12

Vijay


2 Answers

You need to #include <vector> and use the qualified name 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:

  • (as commented by EitanT) I removed the additional qualification a:: on the constructor
  • have a read of Why is "using namespace std" considered bad practice?
like image 187
hmjd Avatar answered Dec 06 '25 03:12

hmjd


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;
}
like image 25
Software_Designer Avatar answered Dec 06 '25 02:12

Software_Designer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!