类内声明,类外定义
使用类内的成员函数给类内的私有成员赋值,并且成员函数在类内声明,类外定义
#include <iostream> using namespace std; class cft { private: float length; float width; float heigth; public: void set_length (); void set_width (); void set_heigth (); void show_tj (); }; void cft::set_length() { cin>>length; } void cft::set_width() { cin>>width; } void cft::set_heigth() { cin>>heigth; } void cft::show_tj() { cout<<length*width*heigth<<endl; } main() { cft a; a.set_length(); a.set_width(); a.set_heigth(); a.show_tj(); return 0; }
构造函数初始化
使用构造函数给长宽高赋值,并计算体积
#include <iostream> using namespace std; class cft { private: float length; float width; float heigth; public: cft (float,float,float); void show_tj (); }; cft::cft (float a,float b,float c) { length=a;width=b;heigth=c; } void cft::show_tj() { cout<<length*width*heigth<<endl; } main() { float a,b,c; cin>>a>>b>>c; cft t(a,b,c); t.show_tj(); return 0; }