c++定义一个名为Person的类?
发布网友
发布时间:2022-11-16 16:17
我来回答
共2个回答
热心网友
时间:2024-11-23 12:01
#include <iostream>
using namespace std;
//这个类独立写在头文件里比较好
class Person
{
private:
char *Name;
float height;
float weight;
public:
Person(){}//构造函数可以不实现
~Person(){}//析构函数也不实现了
//并且有如下公有成员函数:
void setPerson(char *n,float h,float w); //设置姓名、身高和体重 strcpy string.h或cstring
void print(); //输出姓名、身高和体重
char* getName(); //取得姓名
void getHeight(float &h);//取得身高
void getWeight(float *w); //取得体重
};
void Person::setPerson(char *n,float h,float w)
{
Name=n;
height=h;
weight=w;
}
void Person::print()
{
cout<<"Name:"<<Name<<" Height:"<<height<<" Weight:"<<weight<<endl;
}
char *Person::getName()
{
return Name;
}
//个人觉得下面两个函数应该直接定义返回值,而不是使用参数
void Person::getHeight(float &h)
{
h=height;
}
void Person::getWeight(float *w)
{
w=&weight;
}
//////////////////////////////////////////////////////////////////////////
//主函数测试
void main()
{
Person p;
p.setPerson("21chenxb",175,60.5);
p.print();
}
热心网友
时间:2024-11-23 12:02
#include <cstring>
#include <iostream.h>
class Person {
private:
char Name[20];
float height;
float weight;
public:
void setPerson(char *n = 0, float h = 1.75f, float w = 65.0f);
void print();
char * getName(void);
void getHeight(float &h);
void getWeight(float *w);
};
void Person::setPerson(char *n, float h, float w)
{
if(n)strcpy(Name, n); height = h; weight = w;
}
void Person::print (void)
{
cout
<< "Mr/Mrs "
<< Name << ": H["
<< height <<"]\tW["
<< weight <<"]" <<endl;
}
char * Person::getName(void)
{
char * n = new char[strlen(Name)];
strcpy(n, Name);
return n;
}
void Person::getHeight(float & h) { h = height; }
void Person::getWeight(float * w) { *w = weight; }
int main(void)
{
Person p; float h = 0.0f, w = 0.0f; char n[20];
cout << "请输入姓名,身高,体重:" ;
cin >> n >> h >> w;
p.setPerson(n, h, w);
p.print ();
h = 0.0f; w = 0.0f;
char * nx = p.getName();
cout << "getName() -> " << nx << endl;
p.getHeight (h);
cout << "getHeight()-> " << h << endl;
p.getWeight (&w);
cout << "getWeight()-> " << w << endl;
return 0;
}