C++小白课本练习5

成员的访问

Box.h

#pragma once
int main();
class Box
{
    
    
public:
	double length;
	void setWidth(double wid);
	double getWidth();
private:
	double width;
};

double Box::getWidth()
{
    
    
	return width;
}
void Box::setWidth(double wid)
{
    
    
	width = wid;
}

第二章课本测试6类成员的访问.cpp

#include <iostream>
#include <string>
using namespace std;
#include "Box.h"
int main()
{
    
    
	Box box;
	//不使用成员函数设置长度
	box.length = 10.0;
	cout << "Length of box:" << box.length << endl;
	//不使用女成员函数设置宽度
	//box.width=10.0 //错误,因为width是私有的
	box.setWidth(10.0);
	cout << "Width of box:" << box.getWidth() << endl;
	return 0;
}

CEmplyee.h

#pragma once
#include <string>
using namespace std;
class CEmployee
{
    
    
private:
	string szName;
	int salary;
public:
	void setName(string);
	string getName();
	void setSalary(int);
	int getSalary();
	int averageSalary(CEmployee);
};
void CEmployee::setName(string name)
{
    
    
	szName = name;
}
string CEmployee::getName()
{
    
    
	return szName;
}
void CEmployee::setSalary(int mon)
{
    
    
	salary = mon;
}
int CEmployee::getSalary()
{
    
    
	return salary;
}
int CEmployee::averageSalary(CEmployee e1)
{
    
    
	return (salary + e1.getSalary()) / 2;
}

第二章课本测试7类成员访问示例.cpp

#include <iostream>
using namespace std;
#include "CEmplyee.h"
int main()
{
    
    
	CEmployee eT, eY;
	//eT.szName = "Tom1234567"; //编译错误,不能直接访问私有成员
	eT.setName("Tom1234567");
	//eT.averageSalary=5000 //编译错误,不能直接访问私有成员
	eT.setSalary(5000);
	cout << eT.getName() << endl;
	eY.setName("Yong7654321");
	eY.setSalary(3500);
	cout << eY.getName() << endl;
	cout << "aver=" << eT.averageSalary(eY) << endl; //输出aver=4250
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42292697/article/details/115037432