2017-04-25 100 views
-1

可能有人请帮我纠正下面的问题。我试图围绕如何创建一个指向新对象内现有对象的指针。我无法获得正确的语法并不断收到错误。在一个类中创建一个指针到另一个对象

这里是我的代码:

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; 
} 
+1

你能编辑帖子以包括你得到的错误吗? –

+4

停下来,深呼吸一下,想一想这个外表多么愚蠢.'name = name;' – user4581301

+0

你错过了你的person变量的名字,并且在它的声明后面有一个分号 - 除此之外,你在找什么? – jdunlop

回答

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 
{ 
    ... 

而且在一般你应该t与您的代码格式保持一致。

相关问题