class的实现示例
我们定义一个 box 类, 定义它的属性为长宽高, 它的方法是计算和打印它的体积
#include <iostream>
class Box {
private:
double length;
double breadth;
double height;
public:
Box(double len, double bre, double hei);
~Box();
double getVolume();
void setVolume(double len, double bre, double hei);
void printVolume();
};
Box::Box(double len, double bre, double hei) {
length = len;
breadth = bre;
height = hei;
std::cout << "obj is being created." << std::endl;
}
Box::~Box() {
std::cout << "obj is being destroyed." << std::endl;
}
double Box::getVolume() {
return length * breadth * height;
}
void Box::setVolume(double len, double bre, double hei) {
length = len;
breadth = bre;
height = hei;
}
void Box::printVolume() {
std::cout << "the volume of this box: " << getVolume() << std::endl;
}
int main() {
Box box1(1.0, 2.0, 3.0);
Box box2(1.0, 2.0, 3.0);
box1.setVolume(1.0, 2.0, 3.0);
box2.setVolume(5.0, 6.0, 7.0);
box1.printVolume();
box2.printVolume();
return 0;
}
转载请注明来源, from goldandrabbit.github.io