// Uppgift: Addera två tal // Nyckelord: Operatoröverlagring, explicit, friend, operator+, operator<< #include using namespace std; class Integer { public: // explicit: Förbjuder att kompilatorn använder till automatisk // typkonvertering explicit Integer(int i) : value(i) {} Integer operator+(Integer const& b); Integer operator+(int b); friend Integer operator+(int a, Integer const& b); // Ambigous! Hanteras av Integer::operator+(int) ! // friend int operator+(Integer const& a, int b); // Ambigous! Hanteras av Integer::operator+(Integer) ! // friend int operator+(Integer const& a, Integer const& b); friend ostream& operator<<(ostream& os, Integer const& i); private: int value; }; Integer Integer::operator+(Integer const& b) { // skapar en ny Integer explicit mha konstruktorn // prova ta bort Integer! // prova ta bort Integer och explicit! return Integer(value + b.value); } Integer Integer::operator+(int b) { return Integer(value + b); } Integer operator+(int a, Integer const& b) { return Integer(a + b.value); } ostream& operator<<(ostream& os, Integer const& i) { return os << i.value; } int main() { Integer a(8); int b = 5; cout << "a = " << a << endl; // operator<<(ostrea&, Integer) cout << "b = " << b << endl; cout << "a + b = " << a + b << endl; // Integer::operator(int) och << cout << "b + a = " << b + a << endl; // operator(int, Integer) och << cout << "a + a = " << a + a << endl; // Integer::operator(Integer) och << return 0; }