Date: May 27th, 2009
Time: 14:10-16:10
Open book; turn off computer & mobile phone
// Class
#include <iostream>
using std::cout;
class CRectangle
{
int left;
int top;
int right;
int bottom;
public:
CRectangle(int l, int t, int r, int b) : left(l), top(t), right(r), bottom(b) {}
int Area() { return (right-left) * (bottom - top); }
};
int main()
{
CRectangle R1(0,0,10,20);
CRectangle R2 = R1;
cout << R2.Area();
}
// Static member of a class
#include <iostream>
using std::cout;
class CList
{
public:
static int count;
void Inc() { count++; }
void Dec() { count--; }
};
int main()
{
CList L2;
L2.count = 527;
L2.Inc();
cout << L2.count << "\n";
}
// const Object of a Class
#include <iostream>
using std::cout;
class CBox
{
public:
int volume;
};
int Compare(CBox B1, CBox& B2)
{
return (B1.volume > B2.volume);
}
int main()
{
const CBox cigar; cigar.volume = 10;
CBox chocolate; chocolate.volume = 20;
if (Compare(cigar, chocolate))
cout << "cigar is larger.\n";
else
cout << "chocolate is larger than or equal to cigar.\n";
}
// Copy Constructor
#include <iostream>
using std::cout;
class CBox
{
public:
int volume;
char* color;
CBox(int v, char* c = "Violet"): volume(v)
{
color = new char[strlen(c)];
strcpy(color, c);
}
};
int main()
{
CBox cigar(10);
CBox chocolate(cigar);
strcpy(chocolate.color, "Cyan");
cout << chocolate.color << "\n";
}
// Operator Overloading
#include <iostream>
using std::cout;
class CList
{
public:
int count;
CList(int i) : count(i) {}
CList operator++() { count+=2; return *this; }
CList operator++(int) { count+=10; return *this; }
};
int main()
{
CList L2(5);
L2++;
cout << L2.count << "\n";
}
// Access Control Under Inheritance
#include <iostream>
using std::cout;
class John
{
protected:
int money;
public:
John(int i) : money(i) {}
};
class Johnson : public John
{
public:
Johnson(int i) : John(i) {}
void Show() { cout << money << "\n"; }
};
int main()
{
Johnson(1500);
Johnson.Show();
}
// Friendship
#include <iostream>
using std::cout;
class CBox
{
private:
int volume;
public:
CBox(int i) : volume(i) {};
friend int main();
};
int main()
{
CBox b1(10);
cout << b1.volume << "\n";
}
// Virtual Function
#include <iostream>
using std::cout;
using std::endl;
class Animal
{
public:
int weight;
Animal(int w = 5) : weight(w) {} ;
int Cost() { return weight; }
void ShowCost() { cout << Cost() << "\n"; }
};
class Wolf : public Animal
{
public:
Wolf() : Animal() {} ;
int Cost() { return weight * 2 ; }
};
int main()
{
Wolf a1;
a1.ShowCost();
}
void CSketcherView::OnDraw(CDC* pDC)
{
CSketcherDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
pDC->Ellipse(50,0, 150, 100);
pDC->Ellipse(0,50, 100, 150);
pDC->Ellipse(50,100, 150, 200);
pDC->Ellipse(100, 50, 200, 150);
pDC->Rectangle(50, 50, 150, 150);
}