参考书目:C/C++规范设计简明教程,P316
目的:编写一个三角形类,测试类的使用
第一步:建立工程,添加Triangle类
头文件为:
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
using namespace std;
class Triangle
{
private:
float fA; //三边
float fB;
float fC;
public:
Triangle();
bool setSideLength(float a, float b, float c);
float getArea();
};
源文件为Triangle.cpp:
#include "Triangle.h"
Triangle::Triangle()
{
fA = 0;
fB = 0;
fC = 0;
}
bool Triangle::setSideLength(float a, float b, float c)
{
if ((a + b > c) && (a + c > b) && (b + c > a))
{
fA = a;
fB = b;
fC = c;
return true;
}
else
{
cout << "Wrong";
return false;
}
}
float Triangle::getArea()
{
float fT = fA + fB + fC;
return sqrt(fT * (fT - fA)* (fT - fB)* (fT - fC));
}
第二步:主文件
//测试三角形类
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "Triangle.h"
using namespace std;
int main()
{
cout << "Hello World!\n";
Triangle triangle;
bool bResult = triangle.setSideLength(3, 4, 5);
if (bResult == true)
{
cout << "面积" << triangle.getArea();
}
getchar();
}
运行结果如下: