Date: May 25th, 2011
Time: 14:10-15:00
Open book; turn off computer & mobile phone
// Operator Overloading
#include <iostream>
using std::cout;
using std::endl;
class CComplex
{
public:
double real;
double imaginary;
CComplex(double a = 0.0, double b = 0):
real(a), imaginary(b)
{ }
CComplex operator+(CComplex w)
{ return CComplex(real - w.real, imaginary - w.imaginary); }
void Show()
{
if (real != 0.0) cout << real;
if (imaginary < 0.0)
cout << imaginary << "i";
else if
(imaginary > 0.0)
cout << "+" << imaginary << "i";
cout << "\n";
}
};
int main()
{
CComplex c1(5,2);
CComplex c2(5,0);
CComplex c3 = c2 + c1;
c1.Show();
c2.Show(); // "cout << 3.0" will display "3".
c3.Show();
}
// Virtual Function
#include <iostream>
using std::cout;
using std::endl;
class Window // Base class
{
public:
void Create()
{ cout <<"Base class Window" << endl; }
};
class CommandButton : public Window
{
public:
virtual void Create() // "Try to Override a C++ function"
{ cout<<"Derived class Command Button" << endl; }
};
void main()
{
Window *x, *y;
x = new Window();
x->Create();
y = new CommandButton();
y->Create();
}
// Virtual Function
#include <iostream>
using std::cout;
using std::endl;
class Window // Base class for C++ virtual function example
{
public:
virtual void Create() // virtual function for C++ virtual function example
{ cout <<"Base class Window" << endl; }
};
class CommandButton : public Window
{
public:
void Create() // "Overridden C++ virtual function"
{ cout<<"Derived class Command Button" << endl; }
};
void main()
{
Window *x, *y;
x = new Window();
x->Create();
y = new CommandButton();
y->Create();
}
void CSketcherView::OnDraw(CDC* pDC)
{
CSketcherDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// Select the brush
CBrush* pOldBrush = (CBrush*)pDC->SelectStockObject(NULL_BRUSH);
for (int i=10; i<60; i+=10)
pDC->Rectangle(i, 60-i, 110-i, 50+i);
}