自考新教材--p78

戏子无情 提交于 2019-12-06 09:58:53

源程序:

#include <iostream>

using namespace std;

 

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;

}

 

int main()

{

Box box;

// 不使用成员函数设置长度

box.length = 10.0;   //正确,因为length是公有的

cout << "Length of box:" << box.length << endl; //输出Length of box:10

//不使用成员函数设置宽度

//box.width=10.0;  //错误,因为width是私有的

box.setWidth(10.0);

cout << "Width of box:" << box.getWidth() << endl;//输出 Width of box:10

system("pause");

return 0;

}

 运行结果:

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!