[英]Creating a pointer within a class to another object
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? 您忘记了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. 通常,您应该尝试与格式化代码的方式保持一致。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.