写出更加规范的C++代码

本文用最简单的Point.h类做一个示例,展示在大项目中应当如何写出更可读的C++代码

  1. 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);  // 如果是自定义类作为参数时,建议使用引用的方式传入参数,如果该参数在函数中无需修改且没有输出,建议加上 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
  1. 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()
{
    // 实例化对象数组
    Point point[3];

    // 对象数组操作
    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;
}
  1. main.cpp:
#include "point.h"

int main()
{
    stackInstantiation();

    return 0;
}
  1. 编译生成可执行文件:

g++ point.cpp main.cpp -o demo -std=c++11

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。