面向对象(Object-Oriented Programming)
What is different?
// C
typedef struct pont3d {
float x;
float y;
float z;
} Point3d;
void Point3d_print(const Point3d* pd);
Point3d a;
a.x = 1; a.y = 2; a.z = 3;
Point3d_print(&a)
// C++
class Point3d {
public:
Point3d(float x, float y, float z);
print();
private:
float x;
float y;
float z;
} ;
Point3d a(1,2,3);
a.print();
OOP Characteristics
- Everything is an object.
- A program is a bunch of objects telling each other what to do by sending messages.
- Each object has its own mamory made up of other objects.
- Every object has a type.
- All objects of a particular type can receive the same messages.
Advantages of OOP
- Communication ( of the interface)
- Protection: ( to the inner part, data)
.cpp & .h
File structure
Stantard header file structure
Header file is a contract between you and the user of your code.
Header file only declare objections( classes, methods, functions, variables etc), but not define them.
/*
* file name: graphics.h
*/
#ifndef GRAPHICS_H//Fuction:PREVENT graphics.h from being repeatedly reference
#define GRAPHICS_H
#include<....>
...
#include"..."
...
void Function1(...);
...
inline();
...
class Box
{
public:
Box();
...
private:
const int a;
int b
...
...
};//Fuction: Declare a class
#endif /*GRAPHICS_H*/
ATTENTION!! : TO prevent duplicate references, IF structure is necessary.
Content of Classsource.cpp
This file defines, or creates, the methods inside the classes. One class corresponds one source file.
/*
* File name: graphics.cpp
*/
#include "graphics.h" //Functions: To tell gcc the corresponding header file
#include <iostream>
using namespace std;
Box::Box {
...
}//Fuction: To define the method Box inside the class Box, which use ::
...