NTU-OOP-Tuts-2024-Cpp/T9Q1_1/main.cpp

71 lines
1.4 KiB
C++
Raw Normal View History

2024-11-05 10:34:51 +08:00
#include <iostream>
using namespace std;
class A {
protected:
int a, b;
public:
A(int x, int y) {
a = x;
b = y;
}
virtual void print();
friend int doubleIt(A a);
2024-11-07 12:18:48 +08:00
// Question 1.B
// Option 1: Member method
A operator+(A z) {
const int new_a = a + z.a;
const int new_b = b + z.b;
return {new_a, new_b};
}
// Option 2: Non-member method
friend A operator+(const A& z, const A& y);
// Question 1.B
2024-11-05 10:34:51 +08:00
};
class B : public A {
private:
float p, q;
public:
B(int m, int n, float u, float v) : A(m, n){
p = u;
q = v;
}
B() : A(0, 0) { p = q = 0; }
void input(float u, float v);
virtual void print(float);
};
void A::print(void) {
cout << "A values : " << a << " " << b << "\n";
}
void B::print(float) {
cout << "B values : " << p << " " << q << "\n";
}
void B::input(float x, float y) {
p = x; q = y;
}
int doubleIt(A a) { return a.a * a.a; }
2024-11-07 12:18:48 +08:00
// Question 1.B
// Option 2: Non-member method
A operator+(const A& z, const A& y) {
const int new_a = z.a + y.a;
const int new_b = z.b + y.b;
return {new_a, new_b};
}
// Question 1.B
2024-11-05 10:34:51 +08:00
int main() {
2024-11-07 12:18:48 +08:00
A a1(10, 20), *ptr; // Try put *ptr in a new line, as "B *ptr;" to see what is happening;
2024-11-05 10:34:51 +08:00
B b1;
b1.input(7.5, 3.142);
ptr = &a1;
ptr->print();
ptr = &b1;
ptr->print();
}