本文用最簡單的Point.h類做一個示例,展示在大項目中應(yīng)當(dāng)如何寫出更可讀的C++代碼
- point.h:
#ifndef _POINT_H_
#define _POINT_H_
#include <iostream>
#include <string>
using namespace std;
class Point{
public:
Point(double x = 0, double y = 0);
Point(const Point &p);
~Point();
void setPoint(const Point &p); // 如果是自定義類作為參數(shù)時专挪,建議使用引用的方式傳入?yún)?shù)等曼,如果該參數(shù)在函數(shù)中無需修改且沒有輸出,建議加上 const际插。
void setPoint(double x, double y);
void setX(double x);
void setY(double y);
double getX() const;
double getY() const;
private:
double x;
double y;
};
void stackInstantiation();
#endif
- point.cpp:
#include "point.h"
Point::Point(double x, double y):x(x), y(y)
{
cout << "Point(double x = " << x << ", double y = " << y << ")" << endl;
}
Point::Point(const Point &p){
cout << "Point(const Point &p:(" << p.x << ", " << p.y << ")" << endl;
this->x = p.x;
this->y = p.y;
}
Point::~Point(){
cout << "~Point():(" << x << ", " << y << ")" << endl;
}
void Point::setPoint(const Point &p) {
this->x = p.x;
this->y = p.y;
}
void Point::setPoint(double x, double y) {
this->x = x;
this->y = y;
}
void Point::setX(double x) { this->x = x; }
void Point::setY(double y) { this->y = y; }
double Point::getX() const{ return x; }
double Point::getY() const{ return y; }
void stackInstantiation()
{
// 實例化對象數(shù)組
Point point[3];
// 對象數(shù)組操作
cout << "p[0]: (" << point[0].getX() << ", " << point[0].getY() << ")" << endl;
cout << "p[1]: (" << point[1].getX() << ", " << point[1].getY() << ")" << endl;
cout << "p[2]: (" << point[2].getX() << ", " << point[2].getY() << ")" << endl;
point[0].setPoint(3, 4);
cout << "p[0]: (" << point[0].getX() << ", " << point[0].getY() << ")" << endl;
}
- main.cpp:
#include "point.h"
int main()
{
stackInstantiation();
return 0;
}
- 編譯生成可執(zhí)行文件:
g++ point.cpp main.cpp -o demo -std=c++11