2021.3.10C++实验课作业

从身边随便找一个物件,将其抽象为类,并实现这个类,具体要求如下:
(1)私有数据成员:
至少设计两个属性
(2)公有成员函数:
无参构造函数:将属性值置空
普通有参构造函数:通过参数给数据成员赋值
拷贝构造函数:通过一个已有对象初始化当前对象
析构函数:可以为空函数
输出:输出所有数据成员
(3)分文件存储类的声明和实现,新建cpp文件写主函数,并在主函数中测试类中所有成员函数。

Human.h

#include <cstdio>
#include <string>

using std::string;

class Human {
private:
	int height;//身高
	int weight;//体重
	string girlfriend;//npy
	string boyfriend;

public:
	//默认构造函数
	Human();
	//普通有参构造函数
	Human(int h, int w, string girl, string boy);
	//拷贝构造函数
	Human(const Human& xxx);

	//析构函数
	~Human();
	//输出函数
	void print();

	void setHeight(int height);
	void setWeight(int weight);
	void setGirlfriend(string girlfriend);
	void setBoyfriend(string boyfriend);

	int getHeight() const;
	int getWeight() const;
	string getGirlfriend() const;
	string getBoyfriend() const;
};

Human.cpp

#include "Human.h"
#include <iostream>

using std::string;
using std::cout;
using std::endl;

//默认构造函数
Human::Human() {
    height = 0;
    weight = 0;
    girlfriend = "";
    boyfriend = "";
}
//普通有参构造函数
Human::Human(int h, int w, string girl, string boy) {
    height = h;
    weight = w;
    girlfriend = girl;
    boyfriend = boy;
}
//拷贝构造函数
Human::Human(const Human& xxx) {
    height = xxx.height;
    weight = xxx.height;
    girlfriend = xxx.girlfriend;
    boyfriend = xxx.boyfriend;
}

//析构函数
Human::~Human() {}
//输出函数
void Human::print() {
    printf("height = %d, weight = %d\n", height, weight);
    cout<<"girlfriend:"<<girlfriend<<endl;
    cout<<"boyfriend:"<<boyfriend<<endl;
}

void Human::setHeight(int height) {
	this->height = height;
}
void Human::setWeight(int weight) {
    this->weight = weight;
}
void Human::setGirlfriend(string girlfriend) {
    this->girlfriend = girlfriend;
}
void Human::setBoyfriend(string boyfriend) {
    this->boyfriend = boyfriend;
}

int Human::getHeight() const {
	return height;
}
int Human::getWeight() const {
	return height;
}
string Human::getGirlfriend() const {
	return girlfriend;
}
string Human::getBoyfriend() const {
	return boyfriend;
}

main.cpp

#include "Human.h"

int main(void) {
	Human nlh, ykl(160,130,"Sxw","TheDi");
	nlh.setHeight(172);
	nlh.setWeight(160);
	nlh.print();
	ykl.print();

	Human dyy(nlh);
	dyy.print();
	return 0;
}
posted @ 2021-03-10 10:20  快乐永恒  阅读(108)  评论(1编辑  收藏  举报