完善Square的两个成员函数的实现,使得程序正确运行:
裁判测试员程序样例:
#include <iostream>
using namespace std;
template <typename T>
class Square {
public:
Square(T width);
T getArea() const;
private:
T m_width;
};
// 请将答案填写在这里
int main() {
int width1;
cin >> width1; // 输入正方形的边长
Square<int> square1(width1);
cout << square1.getArea() << endl; // 输出正方形的面积
double width2;
cin >> width2; // 输入正方形的边长
Square<double> square2(width2);
cout << square2.getArea() << endl; // 输出正方形的面积
return 0;
}
输入样例:
在这里给出一组输入。例如:
3
1.1
输出样例:
在这里给出相应的输出。例如:
9
1.21
代码如下:
template <typename T>
T Square<T>::getArea() const{
return m_width*m_width;
}
template <typename T>
Square<T>::Square(T width){
m_width=width;
}
注意:我们要知道typename跟class这两个关键字是一样的,也可以把上面的typename改成class都是可以的。T Square<T>::getArea():这部分定义了函数的名称、所属类和返回类型。T是一个模板参数,表示这个类可以接受任何类型的对象。Square<T>:: 表示这个函数是Square类的一个成员。