C++ 入门(一)

108 阅读1分钟

通过一个例子来认识一下C++中的头文件,源文件,可执行程序。

我的工程目录

D:.
├─.idea
├─cmake-build-debug
├─include
├───circle.h
├─src
├───circle.cpp
├─main.cpp

1. 头文件

头文件基本都是以下面的格式来写

#ifndef LCPP_CIRCLE_H
#define LCPP_CIRCLE_H
// code here
#endif //LCPP_CIRCLE_H

我们在.h文件中,一般只声明,不实现。类似接口文件,或抽象类。

#ifndef LCPP_CIRCLE_H
#define LCPP_CIRCLE_H
class Circle{
private:
    double r;
public:
    Circle();
    Circle(double R);
    double  Area();
};


#endif //LCPP_CIRCLE_H

2. 源文件

上面在.h头文件中声明的方法,在源文件中实现。

#include "../include/Circle.h"

Circle::Circle() {
    this->r = 5.0;
}

Circle::Circle(double R) {
    this->r = R;
}

double Circle::Area() {
    return 3.14 * r * r;
}

3. main函数

#include <iostream>
#include "./include/circle.h"
using namespace std;

int main(int argc, char * * argv)
{
    Circle c(3);
    cout << "Area=" << c.Area() <<endl;
    cout << "welcome to C++" << endl;
    return 0;
}