I don't understand why the following code doesn't work: no error, it just send me the following results:
Hello world! Process returned -1073741819 (0xC0000005) execution time : 1.656 s Press any key to continue.
I defined listInt as a vector in private member. Is it coming from the pointer that I use to define the Class1 object?
#include "Class1.h"
using namespace std;
Class1::Class1()
{
int age(10);
listInt[0]=age;
cout <<"address Vector1: "<<&listInt[0] << " - value1:"<<listInt[0] << endl;
}
Class1::~Class1()
{
//delete listInt;
}
void Class1::ClassPrintOut() const
{
cout << listInt[0] << endl;
}
Class1.cpp
#ifndef CLASS1_H_INCLUDED
#define CLASS1_H_INCLUDED
#include <vector>
#include <iostream>
class Class1
{
public:
Class1();
~Class1();
void ClassPrintOut() const;
private:
std::vector<int> listInt;
};
#endif
Main.cpp
#include <iostream>
#include "Class1.h"
using namespace std;
int main()
{
cout << "Hello world!" << endl;
Class1 *test(0);
test =new Class1();
test->ClassPrintOut();
delete test;
return 0;
}
You did not explicitly initialize your std::vector<int> listInt
member. This means the default constructor of std::vector<int>
will be used. It initializes a vector with initial size of 0, thus accessing it with index 0
is invalid.
To give a initial size to your list, you should do:
Class1::Class1() : listInt(/* the initial size */) { ... }
This gives you a vector with size of /* the initial size */
and all elements initialized to zero.
If you want to change the size by dynamically adding elements, use push_back
or emplace_back
:
listInt.push_back(/* element to add */);
listInt.emplace_back(/* element to add */);
Both append an element to the end of the vector and increase the vector's size by one.
The difference is that emplace_back
constructs the new element in-place using the parameters you passed to it, but push_back
always copies (or move) the element. In your case (std::vector<int>
), they make no difference.
User contributions licensed under CC BY-SA 3.0