2017-04-25 106 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與您的代碼格式保持一致。

相關問題