May someone please help me correct the following. I'm trying to wrap my head around how to create a pointer to an existing object within a new object. I can't get the syntax correct and keep getting errors.
Here's my code:
class Country
{
string name;
public:
Country (string name)
{ name = name;
cout << "Country has been created" << endl;}
~Country()
{cout << "Country destroyed \n";}
};
class Person
{
//string name;
//Date dateOfBirth;
Country *pCountry;
public:
Person(Country *c):
pCountry(c)
{}
};
int main()
{
Country US("United States");
Person(&US)
return 0;
}
Did you forget in your main.cpp?
#include <string>
#include <iostream>
using namespace std;
you also need a semicolon in your main:
int main()
{
Country US("United States");
Person person(&US); // < -- variable name and semicolon missing
return 0;
}
You should also change:
Country (string name)
{
this->name = name; // <-- assign name to member variable
...
or better, use member initializer lists :
Country (string name) : name(name) // <-- assign name to member variable
{
...
And in general you should try to be consistent with the way you format your code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.