2017-06-19 162 views
0

我有這個代碼「for」一家銀行。它按照日期和個人信息的兩種結構進行組織。關於銀行賬戶的信息被組織在一個班級中。我需要用預定義的參數編寫一個默認構造函數。該類包含一個struct類型的數據成員,我不知道如何初始化struct類型的數據成員。這是我的代碼。類型成員的默認構造函數的默認參數struct

struct Date { 
    int day, month, year; 
}; 

struct Person { 
    char name[20]; 
    char surname[20]; 
    int IDnum[13]; 
    Date dateBirth; 
}; 

class BankAccount { 
public: 
    BankAccount(????Person p????, int s = 0, bool em = true, int sal = 0) { 
     ??sth for Person p I guess?? 
     sum = s; 
     employed = em; 
     salary = sal; 
    } 
private: 
    Person person; 
    int sum; 
    bool employed; 
    int salary; 
}; 

我希望每一個幫助。提前致謝。

+0

相關/ dupe:https://stackoverflow.com/questions/15307954/default-value-for-struct-parameter – NathanOliver

+0

是的,我看到這篇文章,但我沒有覺得它有幫助,因爲我不明白它。結構中的構造函數? – Winston

+1

C++中'struct'和'class'的區別只是默認可見性:'public' vs'private'。 – Jarod42

回答

1

這是你初始化struct/class變量時使用相同的語法。

BankAccount(Person p = {"John", "Doe", {1,2,3,/*...*/}, {1,1,2000}}, int s = 0, bool em = true, int sal = 0) 

如果一些初始化丟失,像Person p = {"John", "Doe"},那麼所有領域缺乏初始化爲零初始化。

這意味着你甚至可以做Person p = {}將所有字段設置爲零。

或者你可以寫Person{...}而不是{...},這是@Curious做的。


另外,如果您正在使用C++,使用std::string s,而不是char陣列。

+0

「將所有字段設置爲零」調用人員構造函數,這是否也適用於char數組。我不太確定我是否理解,或者將它們設置爲'\ 0'或空字符串「」? – Winston

+0

@Winston Both。所有符號都設置爲「'\ 0''(又名'0'),這使得字符串爲空。 (如果是空字符串,則表示實際爲''「',而不是空格'」「')。 – HolyBlackCat

+0

是的,那是我的錯,我不是指空格,只是空字符串」「。 – Winston

1

結構和類幾乎是在C++一樣的東西,結構可以有構造函數這是你應該做的事情在這種情況下

class BankAccount { 
public: 
    BankAccount(const Person& p = Person{...}, int s = 0, bool em = true, int sal = 0) 
      : person{p}, sum{s}, employed{em}, salary{sal} {} 
private: 
    Person person; 
    int sum; 
    bool employed; 
    int salary; 
}; 

您還可以在類定義的成員變量提供初始化本身,例如

struct Something { 
    int integer{1}; 
    bool boolean{false}; 
}; 
+0

我不喜歡粗魯,但你能解釋一下你的意思:const Person&p = Person {...}。這是什麼意思人{...}? – Winston

+0

@Winston它將具有與上述答案相同的含義。使用它期望的參數 – Curious