類內聲明,類外定義
使用類內的成員函數給類內的私有成員賦值,並且成員函數在類內聲明,類外定義
#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; }