请有人帮我纠正以下问题。我试图围绕如何在新对象中创建指向现有对象的指针。我无法使语法正确并且不断出错。
这是我的代码:
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;
}
答案 0 :(得分:2)
你在main.cpp中忘记了吗?
#include <string>
#include <iostream>
using namespace std;
你还需要一个分号:
int main()
{
Country US("United States");
Person person(&US); // < -- variable name and semicolon missing
return 0;
}
您还应该更改:
Country (string name)
{
this->name = name; // <-- assign name to member variable
...
或更好,请使用member initializer lists:
Country (string name) : name(name) // <-- assign name to member variable
{
...
通常,您应该尝试与格式化代码的方式保持一致。