#20类和对象
#include <iostream>using namespace std;class Box{public: //公有 double length; //ctrl+e复制本行 double width;double height;void getVolume(){ //方法带() cout<<"盒子体积为:"<<length*width*height<<endl; } }; int main(){Box box1;Box box2;box1.height=22.2;box1.width=12.2;box1.length=2.2;box1.getVolume();return 0;
}
#21类成员函数
#include <iostream>
using namespace std;class Box{private: //私有,无法直接调用 double length;double width;double height;public:void setLength(int len); //公有,可调用,具体调用方法可外面写 void setWidth(int wid); void setHeight(int hei); double getVolume();
};void Box::setLength(int len){ //::范围解析运算符 length=len; //length是私有的,len是可以赋值的,传到私有
} void Box::setWidth(int wid){width=wid;
}void Box::setHeight(int hei){height=hei;
}double Box::getVolume(){return length*width*height;
} int main(){Box box1;box1.setLength(10.1);box1.setWidth(11.1);box1.setHeight(12.1);double volume=box1.getVolume();cout<<"盒子体积为:"<<volume<<endl;return 0;
}