c++, 如何run一个c++程序

1 如何run一个c++程序:

  1. 编译: g++ main.cpp a.cpp b.cpp -o main.exe //将main函数, 以及涉及到的cpp文件都写在这(注意是.cpp, 不是.h), 使用g++编译, 输出main.exe文件.
  2. 运行: ./main.exe

2 .cpp和.h文件如何分工:

2.1 主函数文件: main.cpp

#include "a.h" //注意include的是.h文件, 内容是对class的声明.

int main()
{
    auto o_a = A(); //实例化一个A
    o_a.show();     //A展示内容
    o_a.o_b.show(); //B展示内容

    return 0;
}

2.2 a.h, 声明class A及成员

#ifndef A_H_
#define A_H_

#include <iostream>

#include "b.h" //代码中用到了class B, 所以要include b.h

class A
{
private:
public:
    int i_a;
    B o_b;

    A();
    void show();
};

#endif

2.3 a.cpp, class A具体实现


#include "a.h" //class A所需要的所有库都在a.h中include? 还是a.h只include声明所需的库, 其它库在a.cpp中include?

A::A()
{
    this->i_a = 10;
    this->o_b = B();
}

void A::show()
{
    std::cout << "A show, i_a=" << this->i_a << std::endl;
}

2.4 b.h, 声明class B及成员

#ifndef B_H_
#define B_H_

#include <iostream>

class B
{
private:
public:
    int i_b;
    B();
    void show();
};

#endif

2.5 b.cpp, class B具体实现

#include "b.h"

B::B()
{
    this->i_b = 20;
}

void B::show()
{
    std::cout << "B show, i_b=" << this->i_b << std::endl;
}
posted @ 2021-07-23 14:54  编程驴子  阅读(462)  评论(0编辑  收藏  举报