面向对象——案例练习(2)求圆的周长和面积的多文件实现
求圆的周长和面积的多文件实现
一个类对应一个头文件和一个.cpp文件,在头文件写类的声明,在.cpp文件中写类的实现。
1 //Circle.h 2 #pragma once 3 4 class Circle 5 { 6 public: 7 //设置半径 8 void set(double r); 9 //得到半径 10 double get(); 11 //得到周长 12 double getCircleGirth(); 13 //得到面积 14 double getCircleArea(); 15 private: 16 double m_r; 17 double m_area; 18 double m_girth; 19 20 };
1 //Circle.cpp 2 3 #include "Circle.h" 4 5 void Circle::set(double r) 6 { 7 m_r = r; 8 } 9 10 //得到半径 11 double Circle::get() 12 { 13 return m_r; 14 } 15 //得到周长 16 double Circle::getCircleGirth() 17 { 18 m_girth = 2 * 3.14*m_r; 19 return m_girth; 20 } 21 //得到面积 22 double Circle::getCircleArea() 23 { 24 m_area = 3.14*m_r*m_r; 25 return m_area; 26 }
//主文件 #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include "Circle.h" using namespace std; int main(void) { Circle c; c.set(10); cout << "圆的半径:" << c.get() << endl; cout << "圆的周长:" << c.getCircleGirth() << endl; cout << "圆的面积:" << c.getCircleArea() << endl; }