一、目的
将整合在一起的cpp文件分开,为大项目集成模块化做准备。原始代码结构:
#include <iostream>
using namespace std;
class Circle
{
private:
double r;
double PI = 3.14159265358;
public:
//构造函数
Circle();
Circle(double radiuas);
~Circle();
double getArea();
double getCir();
};
//构造函数
Circle::Circle()
{
this->r = 1;
cout << "无参构造函数" << endl;
}
Circle::Circle(double radiuas)
{
this->r = radiuas;
cout << "有参构造函数" << endl;
}
Circle::~Circle()
{
cout << "析构释放内存" << endl;
}
double Circle::getArea()
{
return PI * this->r * this->r;
}
double Circle::getCir()
{
return 2 * this->PI * this->r;
}
//主函数
int main()
{
Circle cir;
Circle cle(4);
cout << "第一类对象面积:" << cir.getArea() << " 周长:" << cir.getCir() << endl;
cout << "第二类对象面积:" << cle.getArea() << " 周长:" << cle.getCir() << endl;
cin.get();
}
二、分离
分离的架构如下:
总共三个文件:主函数文件、类属性头文件、类方法定义文件
头函数:定义类的属性、方法等,注意文件名
#pragma once
//#ifndef _CIRCLE_H
#define _CIRCLE_H
#include<iostream>
using namespace std;
class Circle
{
private:
double r;
double PI = 3.14159265358;
public:
//构造函数
Circle();
Circle(double radiuas);
~Circle();
double getArea();
double getCir();
};
函数定义:先引入头函数定义的属性及方法,随后在一个单独的文件中具体定义方法执行
#include "Circle.h"
using namespace std;
//构造函数
Circle::Circle()
{
this->r = 1;
cout << "无参构造函数" << endl;
}
Circle::Circle(double radiuas)
{
this->r = radiuas;
cout << "有参构造函数" << endl;
}
Circle::~Circle()
{
cout << "析构释放内存" << endl;
}
double Circle::getArea()
{
return PI * this->r * this->r;
}
double Circle::getCir()
{
return 2 * this->PI * this->r;
}
主函数:引入头函数
#include <iostream>
#include "Circle.h"
using namespace std;
int main()
{
Circle cir;
Circle cle(4);
cout << "第一类对象面积:" << cir.getArea() << " 周长:" << cir.getCir() << endl;
cout << "第二类对象面积:" << cle.getArea() << " 周长:" << cle.getCir() << endl;
cin.get();
}
三、执行
正常执行:
Comments NOTHING