Reputation: 107
So I am very new at C++ and I have been given a task of creating a class along with its header file so test.h and test.cpp. Now I need to create a constructor that takes a vector of doubles as an argument and uses it to initialise the object. However, I am not able to figure out how to accurately do this. This is what I have added on my header and cpp class and I'm getting an error
Header file:
#include <string>
#include <vector>
using namespace std;
class Dog
{
int age;
string name;
vector<long double> myVector;
public:
Dog();
Dog(string name, int age, vector<long double> myVector);
};
#endif // DOG_H
cpp file:
using namespace std;
Dog::Dog()
{
cout << "Dog object created"<< endl;
}
Dog::Dog(string name, int age, vector<long double> myVector)
: name(name), age(age), myVector(myVector.push_back(myVector))
{
cout << name<<" "<< age <<" "<<myVector<< endl;
}
now in my main class if i add this:
Dog d("Kelly",3,988);
and run the program I get the no match for operator error.
Upvotes: 1
Views: 394
Reputation: 7271
You need to pass in the third parameter as a vector, or as something that can be used in the constructor of a vector.
If you want a vector with one element of 988 then use:
Dog d("Kelly", 3, { 988 });
This uses an initializer list which a vector can be constructed from.
This will highlight another problem, that the myVector
member variable is not correctly initialised in the initializer list. Instead this should look something like:
Dog::Dog(string name, int age, vector<long double> v) : name(name), age(age), myVector(v)
This copies the elements in the parameter v
into myVector
.
It is also recommended not to have a using namespace std
in header files. This is because anyone who #include <Dog.h>
will end up with the std
namespace at the top level. Check out this answer: https://stackoverflow.com/a/1453605/1517648
Upvotes: 3