自考新教材--p78

源程序:

#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;

}

 运行结果:

原文地址:https://www.cnblogs.com/duanqibo/p/11975580.html