C++类与对象的第二个简单的实战练习-3.24笔记
哔哩哔哩C++面向对象高级语言程序设计教程(118集全)
实战二
Cube.h
#pragma once
class Cube
{
private:double length;double width;double height;
public:double area(void);double Volume(void);//bool judgement(double L1, double W1, double H1);bool judgement(const Cube &ob);//采用引用整体类的方式,节约空间void set(void);void get(void);double getL(void);double getW(void);double getH(void);};
cube.cpp
#include "Cube.h"
#include<iostream>
using namespace std;
double Cube::area(void)
{double result1;result1 = 2 * (length * width + length * height + height * width);cout << "面积为:" << result1 << endl;return result1;}double Cube::Volume(void)
{double result2;result2 = length * width * height;cout << "体积为:" << result2 << endl;return result2;
}bool Cube::judgement(const Cube &ob)
{if ((ob.length == length) && (ob.width == width) && (ob.height == height)) {return 1;}else return 0;
}void Cube::set(void)
{int L, H, W;cout << "请先输入长宽高,长是:" << endl;cin >> L;length = L;cin.ignore();cout << "高是:" << endl;cin >> H;height = H;cin.ignore();cout << "宽是:" << endl;cin >> W;width = W;cout << "输入完毕" << endl;
}void Cube::get(void)
{cout << "你输入的内容是length = " << length << ", width = " << width << ", height = " << height << endl;
}double Cube::getL(void)
{return length;
}double Cube::getW(void)
{return width;
}double Cube::getH(void)
{return height;
}
main.cpp
#include"Cube.h"
#include<iostream>
using namespace std;//在全局函数中不可以通过对象直接访问私有成员,但是可以通过对象的方法间接访问私有数据
bool myjudgement(Cube& ob1, Cube& ob2)
{if ((ob1.getL() == ob2.getL()) && (ob1.getW() == ob2.getW()) && (ob1.getH() == ob2.getH())) {return 1;}else return 0;
}int main() {//实例化两个对象Cube ob1;Cube ob2;//获取第一个立方体的具体信息并打印出来cout << "第一个立方体" << endl;ob1.set();ob1.get();//获取第二个立方体的具体信息并打印出来cout << "第二个立方体" << endl;ob2.set();ob2.get();//输出第一个立方体的面积和体积ob1.area();ob1.Volume();//利用成员函数判断两个立方体是否相等if (ob1.judgement(ob2)) {cout << "两个立方体完全相等" << endl;}else cout << "两个立方体不完全相等" << endl;//利用全局函数判断两个立方体是否相等if (myjudgement(ob1, ob2)) {cout << "两个立方体完全相等" << endl;}else cout << "两个立方体不完全相等" << endl;
}
总结
- 利用全局函数和类的成员函数比较两个实例化对象的不同
- 引用类作为函数的形参
- 用const修饰传入的参数,在函数内部不可修改