そこそこマジメに手直ししてみた。
C++
1#include <string>
2#include <iostream>
3
4class Location{
5private:
6 int x_;
7 int y_;
8public:
9 Location(int x, int y) : x_(x), y_(y) {}
10 Location(const Location& loc) : x_(loc.x_), y_(loc.y_) {}
11 Location& operator=(const Location& rhs) { x_ = rhs.x_; y_ = rhs.y_; return *this; }
12 void setx(int x) { x_ = x; }
13 void sety(int y) { y_ = y; }
14 int getx() const { return x_; }
15 int gety() const { return y_; }
16};
17
18// Locationの比較: a == b
19inline bool operator==(const Location& a, const Location& b) {
20 return a.getx() == b.getx() && a.gety() == b.gety();
21}
22
23// Locationの比較: a != b
24inline bool operator!=(const Location& a, const Location& b) {
25 return !(a == b);
26}
27
28// Locationの出力: stream << loc
29std::ostream& operator<<(std::ostream& stream, const Location& loc) {
30 return stream << '(' << loc.getx() << ',' << loc.gety() << ')';
31}
32
33class Student {
34protected:
35 std::string name_;
36 int id_;
37 float gpa_;
38 Location loc_;
39public:
40 Student(const std::string& name,int id, float gpa, Location loc)
41 : name_(name), id_(id), gpa_(gpa), loc_(loc) {}
42 void print_to(std::ostream& stream) const;
43 void set_gpa(float gpa) { gpa_ = gpa; }
44 float get_gpa() const { return gpa_; }
45};
46
47void Student::print_to(std::ostream& stream) const {
48 stream << name_ << " #" << id_ << " ?" << gpa_ << " @" << loc_;
49}
50
51// Studentの差(gpaの差)
52inline float operator-(const Student& a, const Student& b) {
53 return a.get_gpa() - b.get_gpa();
54}
55
56inline std::ostream& operator<<(std::ostream& stream, const Student& stu) {
57 stu.print_to(stream); return stream;
58}
59
60/*
61 * おためし
62 */
63int main() {
64 using namespace std;
65 Student a("alice", 123, 56.7f, Location(12,34));
66 Student b("bob", 456, 67.8f, Location(23,45));
67 cout << a << endl;
68 cout << b << endl;
69 cout << "a - b = " << a - b << endl;
70}
71
72/* 実行結果
73alice #123 ?56.7 @(12,34)
74bob #456 ?67.8 @(23,45)
75a - b = -11.1
76*/