I have this code "for" a bank. It is organized in two structures for date, and personal information about person. The information about the bank account is organized in a class. I need to write a default constructor with predefined arguments. The class contains a data member of type struct and I don't know how to initialize the data member of type struct. Here is my code.
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;
};
I would appreciate every help. Thanks in advance.
Structs and classes are almost the same thing in C++, structs can have constructors which is what you should do in this situation
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;
};
You can also provide initializers for member variables in the class definition itself, for example
struct Something {
int integer{1};
bool boolean{false};
};
It's the same syntax you use when initializing a struct
/ class
variable.
BankAccount(Person p = {"John", "Doe", {1,2,3,/*...*/}, {1,1,2000}}, int s = 0, bool em = true, int sal = 0 )
If some initializers are missing, like Person p = {"John", "Doe"}
, then all fields lacking initializers are zero-initialized.
It means you could even do Person p = {}
to set all fields to zeroes.
Optionally you can write Person{...}
instead of {...}
, which is what @Curious did.
Also, if you're using C++, please use std::string
s instead of char
arrays.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.