class Person {
public:
Person(string n, int a) {
name = n;
age = a;
}
private:
string name;
int age;
};
class Car{
public:
Car(string m, Person* ps, Person* pss) {
model = m;
owner = ps;
driver = pss;
}
private:
string model;
Person* owner;
Person* driver;
};
I don't want to post the whole code, so later down the line i have:
1 2 3 4 5
cin >> model >> owner >> driver;
Person* o = owner;
Person* d = driver;
Car* a = new Car(model, o, d);
cars.push_back(a);
"cars" is a vector. I want to read 3 strings - model owner driver and write them down into the cars vector. The problem is that i get the following error:
No suitable conversion function from "std:string" to "Person*" exists.
What function do i need to write in order to assign a string variable to the owner and driver objects that i have in my Car class?
the pointers is a really bad approach -- avoid dynamic memory if you can (and, you can here!) That aside, what you need is a setter for owner and driver.
what you need is for 'person' object to have a constructor or setter to assign its private member string to owner/driver after line 3 above. eg
o[0].setsomething(owner);
d[0].setsomething(driver);
you can almost do it, but person ctor expects an age you don't have. if you read in the ages, you can do it as-is:
person* o = new person(owner, oage);
person* d = new person(driver, dage);
what you have currently is trying to put a string into a pointer, which won't work. you need to allocate the owner and driver.
#include <iostream>
#include <string>
#include <vector>
class Person
{
public:
Person(std::string n, int a)
{
name = n;
age = a;
}
private:
std::string name;
int age;
};
class Car
{
public:
Car(std::string m, std::string ps, std::string pss)
{
model = m;
owner = ps;
driver = pss;
}
private:
std::string model;
std::string owner;
std::string driver;
};
int main()
{
std::vector<Car> cars;
std::string model, owner, driver;
std::cout << "\n Enter model name: ";
std::getline(std::cin, model);
std::cout << "\n Enter owner name: ";
std::getline(std::cin, owner);
std::cout << "\n Enter driver: ";
std::getline(std::cin, driver);
cars.emplace_back(model, owner, driver);
return 0; // <--- Not required, but makes a good break point.
}
I used "std::getline" because any of those variables could have a space in it.
Using the "emplace_back" this makes use of the overloaded ctor to first create an object of the class before storing it in the vector. A bit easier.
In the class I changed the pointers to "std::stings" because I know of no way of converting a "std::string" to a "Person *".
Without the rest of the code or a better explaination of the program I am not sure what you are trying to do or why you feel that "owner" and "driver" need to be "Person *"s.