71 lines
1.4 KiB
C++
71 lines
1.4 KiB
C++
#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);
|
|
|
|
// 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
|
|
};
|
|
|
|
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; }
|
|
|
|
// 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
|
|
|
|
|
|
int main() {
|
|
A a1(10, 20), *ptr; // Try put *ptr in a new line, as "B *ptr;" to see what is happening;
|
|
B b1;
|
|
b1.input(7.5, 3.142);
|
|
|
|
ptr = &a1;
|
|
ptr->print();
|
|
ptr = &b1;
|
|
ptr->print();
|
|
}
|