Introduction to Classes
It is C++ classes that make possible encapsulation, data hiding, inheritance and what C++ is all about.
Classes are an extension of structures. A class is a user-defined type. Classes include both data members and member functions.
Structures
struct thing
{
int a;
char b;
float c;
};
.
.
.
int main (void)
{
int i;
thing x;
thing y;
thing stuff[10];
thing * ptr_to_a_thing;
.
.
.
x.a = 5;
y.c = 3.14;
.
.
.
ptr_to_a_thing = &y;
i = (*ptr_to_a_thing).a; // same as i = ptr_to_a_thing->a;
.
.
.
The Class Definition
Class members, functions and data, are identified with an access-specifier, private, public, or protected. Private and protected members may only be accessed by member functions of the class (except for friend functions). Public members may be accessed wherever they are "in scope".
Class member functions are defined using the class name and the scope resolution operator ::
A class definition describes what a class is and what it does, or maybe what you can do to it. It consists of the keyword class, followed by a class name, opening and closing braces and a semicolon at the end. It may contain members, similar to a struct. The members are of two types, data and functions. It may also contain access specifiers, type definitions, nested classes, and possibly the specifications of friend functions.
class thing {
private: // it's most common for data members
int a; // to be private or protected
char b;
float c;
protected: // protected members used with inheritance
(some data and functions)
public:
void funk1(void); // member function prototypes
void funk2(int);
int funk3(float,char,int);
};
// member function definitions
void thing::funk1(void)
{
...
}
void thing::funk2(int x)
{
...
}
int thing::funk3(float f, char ch, int i)
{
...
}
.
int main (void)
{
thing one, two, three;
thing array[10];
one.funk1(); // What is this?
// one.a = 5; // Why won't this work?
What are one, two, three and array?
Class Examples
Example 3-1 - The circle class
1 // File: ex3-1.cpp - the circle class
2
3 #include <iostream>
4 using namespace std;
5
6 class circle
7 {
8 private:
9 double radius;
10 public:
11 void store(double);
12 double area(void);
13 void display(void);
14 };
15
16 // member function definitions
17 void circle::store(double r)
18 {
19 radius = r;
20 return;
21 }
22
23 double circle::area(void)
24 {
25 return 3.14 * radius * radius;
26 }
27
28 void circle::display(void)
29 {
30 cout << radius << endl;
31 return;
32 }
33
34 int main(void)
35 {
36 circle c; // instance (object) of circle class
37 c.store(5.0);
38 cout << "The area of circle c is " << c.area() << endl;
39 cout << "Circle c has radius ";
40 c.display();
41 return 0;
42 }****** Output ******
The area of circle c is 78.5
Circle c has radius 5
Class Definition Notes
- The default access specifier is private, so if an access specifier does not appear before class members, then the members are private.
- Members, public, private, or protected, may appear in any order in the class definition. Further, access specifiers may be repeated within the class definition.
- Private members are not accessible (visible) to functions that are not members of the the class. This principle is referred to as data hiding.
- Member functions are defined after the class definition, or in a separate file, that "includes" the class definition.
- A semicolon is required at the end of each declaration, function or data member, within the class definition. An exception to this rule involves implicit inline functions. Further, it is possible to declare multiple data members of the same type using a comma to separate them.
- Data members are usually private or protected. A public data member does not have the protection of the class. Functions are may be public, private or protected. Public member functions are part of the class interface. Clients (other non-class functions) may only access class objects using the public member functions. Member functions may be private. A private member function may only be accessed by another member function of the same class. The exception to this is a friend function (to be discussed later).
- Classes and structs are the same in C++ with one exception. In classes, the default access specifier is private, in structs, it's public.
- Member functions are also called methods, behaviors or messages
- Variables or instances of a classes that are declared in a program are called objects. Member functions may be executed using a class object or by dereferencing a pointer to a class object.
class X
{
public:
int funk(); // a member function
};
…
X ray;
X* pX;
pX = &ray;
ray.funk(); // execution of a member function using an object
pX->funk(); // execution of a member function using a pointer
// to a class object
Example 3-2 - The triangle class
1 // File ex3-2.cpp - the triangle class
2
3 #include <iostream>
4 using namespace std;
5
6 class triangle
7 {
8 private:
9 double base;
10 double height;
11 double area;
12 public:
13 void store(double, double);
14 void calc_area(void);
15 void show(void);
16 };
17
18 // member function definitions
19 void triangle::store(double b, double h) {
20 base = b;
21 height = h;
22 return; // “return” is optional
23 }
24
25 void triangle::calc_area(void) {
26 area = .5 * base * height;
27 return;
28 }
29
30 void triangle::show(void) {
31 cout << "base = " << base;
32 cout << " height = " << height;
33 cout << " area = " << area << endl;
34 return;
35 }
36
37 int main(void)
38 {
39 triangle t; // an instance of the triangle class
40 t.store(1.23,4.55); // initialize triangle t
41 t.calc_area(); // calculate the area of triangle t
42 t.show(); // display triangle t data
43 return 0;
44 }****** Output ******
base = 1.23 height = 4.55 area = 2.79825
Example 3-3 - The fraction Class
1 // File: ex3-3.cpp - the fraction class
2
3 #include <iostream>
4 #include <cstdlib> // for abs()
5 using namespace std;
6
7 class fraction {
8 public:
9 void set(int n, int d);
10 void display(void);
11 void add(fraction&, fraction&);
12 void subtract(fraction&, fraction&);
13 void multiply(fraction&, fraction&);
14 void divide(fraction&, fraction&);
15 void reduce(void);
16 private:
17 int numer; // numerator
18 int denom; // denominator
19 };
20
21 void fraction::set(int n, int d)
22 {
23 numer = n;
24 denom = d;
25 return;
26 }
27
28 void fraction::display(void)
29 {
30 cout << numer << '/' << denom << endl;
31 return;
32 }
33
34 void fraction::add(fraction& f1, fraction& f2)
35 {
36 numer = f1.numer * f2.denom + f2.numer * f1.denom;
37 denom = f1.denom * f2.denom;
38 return;
39 }
40
41 void fraction::multiply(fraction& f1, fraction& f2)
42 {
43 numer = f1.numer * f2.numer;
44 denom = f1.denom * f2.denom;
45 }
46
47 void fraction::reduce()
48 {
49 int min; // the minimum of the denom and numer
50 min = abs(denom) < abs(numer) ? abs(denom) : abs(numer);
51 for (int i = 2; i <= min; i++)
52 {
53 while ((abs(numer) % i == 0) && (abs(denom) % i == 0))
54 {
55 numer /= i;
56 denom /= i;
57 }
58 }
59 return;
60 }
61
62 int main(void)
63 {
64 fraction f,g,h; // declare fractions f, g, and h
65 f.set(3,4); // initialize fraction f & g
66 g.set(7,20);
67 f.display(); // display fraction f
68 g.display();
69 h.add(f,g); // h = f + g
70 h.display();
71 h.reduce(); // reduce h
72 h.display();
73 h.multiply(f,g); // h = f * g
74 h.display();
75 int i,j;
76 cout << "Enter a fraction numerator and denominator => ";
77 cin >> i >> j;
78 h.set(i,j);
79 h.multiply(h,h);
80 cout << i << '/' << j << " squared is ";
81 h.display();
82 return 0;
83 }****** Sample Run ******
3/4
7/20
88/80
11/10
21/80
Enter a fraction numerator and denominator => 2 3
2/3 squared is 4/9
Why use fraction& arguments instead of fraction?
Should add's arguments be const fraction& instead of fraction&?
What if you tried to add a fraction to itself? f1.add(f1,f2) ?
How would you write the subtract and divide member functions?
Here's another implementation of the reduce() function for example 3-3. It implements the Euclidean Algorithm for determining the greatest common divisor of the fraction's numberator and denominator.
1 void swap(int& x, int& y)
2 {
3 int temp;
4 temp = x;
5 x = y;
6 y = temp;
7 }
8
9 int gcd (int x, int y)
10 {
11 if (x < y) swap(x,y);
12 int rem = x % y;
13 while (rem > 1) {
14 return gcd(y,rem); // Note recursive call to gcd()
15 }
16 return y;
17 }
18
19 void fraction::reduce(void)
20 {
21 int divisor = gcd(numer,denom);
22 numer /= divisor;
23 denom /= divisor;
24 return;
25 }1. default access specifier is private.
2. Members, public, private, or protected 在 class definition 內有次序的排列.
3. Private members 只可以被 class member functions 使用.
4. Member functions 在 class 定義後定義.
5. Semicolon 必須出現在 declaraion, function, or data member 後. inline function 是例外.
6. Data members 通常為 private or protected. Functions 為 public, private, or protected. Friend function 為例外.
7. Classes 和 structs 在 C++ 都一樣, 唯一的例外是: classes 的 default access specifier 為 private; structs 是 public.
8. Member functions 也可以稱為 methods, behaviors, or messages.
9. 在 program 中 declar 的 class variables or instances 為 objects.
沒有留言:
張貼留言