Date: May 27th, 2009
Time: 08:30-10:30
Open book; turn off computer & mobile phone
// Class
#include <iostream>
using std::cout;
class CRectangle
{
int left;
int top;
int right;
int bottom;
public:
int Area() { return (right-left) * (bottom - top); }
};
int main()
{
CRectangle R1(0,0,10,20);
cout << R1.Area();
}
// Static member of a class
#include <iostream>
using std::cout;
class CList
{
public:
static int count;
void Inc() { count++; }
void Dec() { count--; }
};
int CList::count = 527;
int main()
{
CList L2;
L2.Inc();
cout << L2.count << "\n";
}
// Reference to Class Object
#include <iostream>
using std::cout;
class CBox
{
public:
int volume;
};
int Compare(CBox B1, CBox& B2)
{
return (B1.volume > B2.volume);
}
int main()
{
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);
cout << chocolate.color << "\n";
}
// Operator Overloading
#include <iostream>
using std::cout;
class CList
{
public:
int count;
CList(int i) : count(i) {}
CList operator++() { count++; return *this; }
CList operator--() { count--; return *this; }
};
int main()
{
CList L2(5);
++L2;
cout << L2.count << "\n";
}
// Access Control Under Inheritance
#include <iostream>
using std::cout;
class John
{
protect:
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 person(1500);
person.Show();
}
// Friendship
#include <iostream>
using std::cout;
class CBox
{
private:
int volume;
public:
CBox() : volume(20) {};
};
int main()
{
friend CBox::CBox();
CBox b1;
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) {} ;
virtual int Cost() { return weight; }
void ShowCost() { cout << Cost() << "\n"; }
};
class Wolf : public Animal
{
public:
Wolf() : Animal() {} ;
virtual 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->Rectangle(50, 50, 150, 150);
pDC->Arc(50,0, 150, 100, 150, 50, 50, 50);
pDC->Arc(0,50, 100, 150, 50, 50, 50, 150);
pDC->Arc(50,100, 150, 200, 50, 150, 150, 150 );
pDC->Arc(100, 50, 200, 150, 150, 150, 150, 50);
}