
CMakeLists.txt

注意 这里是是使用了 box.cpp 并没有连接h
add_executable(demo1 example.cpp box.cpp)
完整内容
# cmake needs this line cmake_minimum_required(VERSION 3.1) # Define project name project(demo) add_executable(demo1 example.cpp box.cpp)
box.h

#ifndef BOX_H
#define BOX_H
#include <iostream>
#include <cmath>
using namespace std;
// Box的定义
class Box
{
public:
//1-1初始化函数
Box(){}//构造函数1
Box(double len,double bre,double hei){ //构造函数2
length=len;
breadth=bre;
height=hei;
cout<<"初始化函数"<<endl;
}
//1-2结束销毁函数
~Box()
{
cout<<"析构函数执行"<<endl;
}
//2普通函数
double get(void);
void set(double len,double bre,double hei);
//正常变量
private:
double length;
double breadth;
double height;
//静态变量
public:
static double result;//所有对象使用一个,节省空间
//int Box::result=10;//静态变量可以初始化,但是只能在类外
static double add1;
static double add2;
//静态函数
//默认c++没有添加this指针
//主要用来访问静态成员
public:
static double static_add();
};
#endif
box.cpp

//#ifndef BOX_H
//#define BOX_H
#include "box.h"
//正常函数
// Box的类外成员函数
double Box::get(void){
return length*breadth*height;
}
// Box的类外成员函数
void Box::set(double len,double bre,double hei){
length = len;
breadth = bre;
height = hei;
}
//静态变量初始化
double Box::result=10;//静态变量可以初始化,但是只能在类外
double Box::add1=11;//静态变量可以初始化,但是只能在类外
double Box::add2=12;//静态变量可以初始化,但是只能在类外
//静态函数
double Box::static_add(){
result =add1+add2; //静态变量可以直接访问,非静态变量没有this指针无法访问
return result;
}
//#endif
example.cpp

#include <iostream>
#include <cmath>
using namespace std;
#include "box.h"
//主函数调用
int main(int argc, char** argv)
{
// box 1-2静态构建
Box box1;
//box1 的函数调用 public可以调用
box1.set(1,2,3);
double result=box1.get();
cout<< "box1的计算结果 "<<result<<endl;
// private 无法调用
//box1.length=1;
//box1.breadth=1;
//box1.height=1;
//1-2 动态创建
Box *box2=new Box(1,2,3);
double result2=box2->get();
cout<< "box2的计算结果 "<<result2<<endl;
//delete box2;//释放内存
// cout<< "box2的释放空间 "<<result2<<endl;
// 2-1静态变量
cout<<"静态变量Box类定义"<<Box::result<<endl; //物理含义 学生平均成绩
cout<<"静态变量静态类box1"<<box1.result<<endl; //物理含义 学生的总人数
cout<<"静态变量动态类box2"<<box2->result<<endl; //物理含义 学生总成绩累加
//2-2静态方法
cout<<"静态函数"<<Box::static_add()<<endl;
}
编译
mkdir build cd build cmake .. make
浙公网安备 33010602011771号