C++学习总结_声明一个对象并实现声明类的方法

来源:互联网 发布:数据分析咨询公司 编辑:程序博客网 时间:2024/06/05 15:57

#include <iostream>
using namespace std;
class Human//声明一个Human类
{

//声明相关的成员方法
public :
 int GetWeight();
 double GetHeight();
 void SetWeight(int x);
 void SetHeight(double y);

//声明相关的成员变量
private:
 int weight;
 double height;
};

//实现所有成员方法,先写该方法返回类型,再写该成员方法属于的类,类名之后要加::,再写方法名和参数及实现
void Human::SetWeight(int x)
{
 weight = x;
}
void Human::SetHeight(double y)
{
 height = y;
}
int Human::GetWeight()
{
 return weight;
}
double Human::GetHeight()
{
 return height;
}

//main方法入口
int main()
{
 Human sam;//声明一个Human类型的对象sam
 sam.SetHeight(1.70);//为sam对象设置身高
 cout<<"sam 的身高是:"<<sam.GetHeight()<<endl;//输出sam的身高
 sam.SetWeight(110);//为sam对象设置体重
 cout<<"sam 的体重是:"<<sam.GetWeight()<<endl;//输出sam的体重
 return 0;
}

特别说明:成员函数的实现其实也可以在该类中写完方法名称就实现,此处只是展示C++支持的一种成员方法实现形式