作业帮 > 综合 > 作业

C++构造函数不能有返回类型

来源:学生作业帮 编辑:搜搜做题作业网作业帮 分类:综合作业 时间:2024/05/12 02:45:47
C++构造函数不能有返回类型
定义一个圆柱体类模版,数据成员有圆柱体底半径,圆柱体高,成员函数有带参数构造函数,求圆柱体体积函数,求圆柱体表面积函数,要求成员函数在类外定义,主程序测试时实例化为float和double型,半径和高从键盘输入
下面是我的代码:
#include
using namespace std;
#define PI 3.14
template
class Cylinder
{
public:
Cylinder(T r,T h);
T area();
T volume();
protected:
T radius,height;
};
------------------------------
#include "Cylinder.h"
template
T Cylinder::Cylinder(T r,T h)
{
radius=r;
height=h;
}
template
T Cylinder::area()
{
return ((PI*radius*radius*2)+(2*PI*radius*height));
}
template
T Cylinder::volume()
{
return (PI*radius*radius*height);
}
-----------------------------
#include "Cylinder.h"
int main()
{
int r,h;
cin>>r>>h;
Cylinder cy(r,h);
cout
C++构造函数不能有返回类型
模板类的定义要放在一个文件中,不能分开来定义.
 
第二
template<class T>T Cylinder<T>::Cylinder(T r,T h){ //class T后多了个T
//Cylinder.h
#include <iostream>
using namespace std;
#define PI 3.14
template <class T> class Cylinder{
public: 
 Cylinder(T r,T h); 
 T area(); 
 T volume();
protected: 
 T radius,height;
};
template<class T> Cylinder<T>::Cylinder(T r,T h){ //class T后多了个T
 radius=r;
 height=h;
}
template<class T>T Cylinder<T>::area(){ 
 return ((PI*radius*radius*2)+(2*PI*radius*height));
}
template<class T>T Cylinder<T>::volume(){ 
 return  (PI*radius*radius*height);

//main.cpp
#include "Cylinder.h"
int main(){ 
 int r,h; 
 cin>>r>>h; 
 Cylinder <float> cy(r,h); 
 
 cout<<cy.area()<<endl; 
 cout<<cy.volume()<<endl; 
 cin>>r>>h; 
 Cylinder <double> cy2(r,h); 
 cout<<cy2.area()<<endl; 
 cout<<cy2.volume()<<endl;    
 return 0; 
}