一.c++求长方柱体积,类外定义成员函数连续求解三个长方体的体积。
代码实现:
#include<iostream>
using namespace std;
class box
{public:
void set_value(); //长方体长宽高输入函数声明
int cal_value();//计算函数声明
void show_value(int v); //打印体积函数声明
private:
int length;int width; int height;
};
void box::set_value()//长方体长宽高输入函数定义
{
cin >> length >> width >> height;
}
int box::cal_value() //计算函数定义
{
int v;
v = length * width * height;
return v;
}
void box::show_value(int v) 打印体积函数定义
{
cout << v;
}
int main()
{
box b1; int v1;//求第一个长方体体积
cout << "请输入第一个长方体的长宽高:" << endl;
b1.set_value();
v1=b1.cal_value();
b1.show_value(v1);
box b2; int v2;
cout << endl<<"请输入第二个长方体的长宽高:" << endl;
b2.set_value();//求第二个长方体体积
v2 = b2.cal_value();
b2.show_value(v2);
box b3; int v3;//求第三个长方体体积
cout << endl<<"请输入第三个长方体的长宽高:" << endl;
b3.set_value();
v3 = b3.cal_value();
b3.show_value(v3);
return 0;
}
运行结果展示:
二.运用类模板在类外定义各成员函数
注意点:
1.类内定义类模板格式:
2.类外定义类模板格式:
代码实现:
#include<iostream>
using namespace std;
template<class numtype>
class Compare
{
public:
Compare(numtype a, numtype b);
numtype max();
numtype min();
//numtype max() { return(x > y) ? x : y; }
//numtype min() { return(x < y) ? x : y; }
private:
numtype x, y;
};//定义了一个Compare类模板
template<class numtype> //在类外定义类模板成员函数求最大值
numtype Compare<numtype>::max()
{
return(x > y) ? x : y;
}
template<class numtype>//在类外定义类模板构造函数
Compare<numtype>::Compare(numtype a, numtype b)//构造函数也可以放在类外定义
{
x = a; y = b;
}
template<class numtype>//在类外定义类模板成员函数求最小值
numtype Compare<numtype>::min()
{
return(x < y) ? x : y;
}
int main()
{
Compare<int>cmp1(3, 7);
cout << cmp1.max() << "是最大的" << endl;
cout << cmp1.min() << "是最小的" << endl;
Compare<float>cmp2(45.78,93.6);
cout << cmp2.max() << "是最大的" << endl;
cout << cmp2.min() << "是最小的" << endl;
Compare<char>cmp3('a', 'A');
cout << cmp3.max() << "是最大的" << endl;
cout << cmp3.min() << "是最小的" << endl;
}
运行结果展示: