1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
#include <iostream>
#include <string>
struct Person {
struct NE {
std::string age;
int height, weight;
NE (const std::string& a, int h, int w) : age(a), height(h), weight(w) {}
NE(const Person& other)
: age(other.getAge()), height(other.getHeight()), weight(other.getWeight()) {}
NE (Person&& other)
: age(std::move(other.getAge())), height(other.getHeight()), weight(other.getWeight()) {}
};
std::string name;
int ID;
NE data; // *** Holds all data of Person that is to be reassigned with operator=.
Person (const std::string& n, int id, const std::string& a, int h, int w) :
name(n), ID(id), data(NE(a,h,w)) {} // Member initializer uses NE(a,h,w) for 'data'.
Person& operator= (NE&& ne) {
std::swap(data, ne); return *this; // No changes need to be made here when NE gets new data members added.
}
Person& assignWithExceptions (const Person& other) {return *this = NE(other);}
Person& assignWithExceptions (Person&& other) {return *this = NE(std::move(other));}
std::string getAge() const {return data.age;}
int getHeight() const {return data.height;}
int getWeight() const {return data.weight;}
void print() const {
std::cout << "Name = " << name << '\n';
std::cout << "ID = " << ID << '\n';
std::cout << "Age = " << getAge() << '\n';
std::cout << "Height = " << getHeight() << '\n';
std::cout << "Weight = " << getWeight() << "\n\n";
}
};
int main() {
Person bob ("Bob", 2047, "38 years and 9 months", 183, 170);
Person frank ("Frank", 5025, "25 years and 2 months", 190, 205);
bob.print();
frank.print();
std::cout << "Bob pretends to be Frank, but keeps his name and ID.\n";
bob.assignWithExceptions (frank);
bob.print();
}
|