//Program 3-1 class rectangle private float widths float lengths float area public: void setData(float, float); void calcarea float getwidth(; float getLength(; float getarea(;
// Program 3-1 class Rectangle { private: float width; float length; float area; public: void setData(float, float); void calcArea( ); float getWidth( ); float getLength( ); float getArea( ); };
∥参数值传递给私有成员变量 void Rectangle: setData( float W, float 1) width=W length =l: ∥计算面积 void Rectangle calcArea() area= width x length
// 参数值传递给私有成员变量 void Rectangle::setData( float w, float l ) { width = w; length = l; } // 计算面积 void Rectangle::calcArea( ) { area = width * length; }
∥返回私有成员变量wdth float Rectangle getwidtho return width ∥返回私有成员变量 length float Rectangle: getLength( return length ∥返回私有成员变量area float Rectangle: getArea() return area:
// 返回私有成员变量width float Rectangle::getWidth( ) { return width; } // 返回私有成员变量 length float Rectangle::getLength( ) { return length; } // 返回私有成员变量 area float Rectangle::getArea( ) { return area; }
void main( i Rectangle box; float wide, box Long cou<<"请输入长和宽?" cin > wide>> boxLong box. setData(wide, boxLong); box. calcArea (; cout<"矩形的数据:n"; cout <<"DE:"<< box getWidth(<<endl cout<<"k: "< box. getLength(<<endl; cout<<"面积:"<< box.getArea()<end; 3-1.cpp
void main( ) { Rectangle box; float wide, boxLong; cout << " 请输入长和宽 ? "; cin >> wide>> boxLong; box.setData(wide, boxLong); box.calcArea( ); cout << "矩形的数据:\n"; cout << "宽: "<< box.getWidth( ) << endl; cout << "长: "<< box.getLength( )<<endl; cout << "面积: "<< box.getArea( )<<endl; } 3-1.cpp
343引入私有成员的原因 在OOP程序设计中,对象保护重要的数据不被破 坏是一件很重要的事情,它是通过将关键数据声 明为私有成员; 当一个成员变量被定义为私有时,唯一对它的访 问途径就是通过公有的成员函数
20 3.4.3 引入私有成员的原因 • 在OOP程序设计中,对象保护重要的数据不被破 坏是一件很重要的事情,它是通过将关键数据声 明为私有成员; • 当一个成员变量被定义为私有时,唯一对它的访 问途径就是通过公有的成员函数