类的封装:
 把变量属性设置成private,把构造函数属性设置为public,在public中设置 内联函数 ,内联函数目的就是一方面可以调用private中的变量,另一方面可以在main函数中被调用,从而实现了函数的封装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| #include<iostream> using namespace std; class Clock { private: int hour, minute, second; public: Clock(); Clock(int newH, int newM, int newS); void setHour(int hour) { this->hour = hour; } void setMinute(int minute) { this->minute = minute; } void setSecond(int second) { this->second = second; } int getHour() { return hour; } int getMinute() { return minute; } int getSecond() { return second; } void display() { cout << hour << ":" << minute << ":" << second << endl; } };
Clock::Clock() { this->hour = 1; this->minute = 1; this->second = 1; }
Clock::Clock(int newH, int newM, int newS) { this->hour = newH; this->minute = newM; this-> second = newS; } int main(void) { Clock myClock_1; cout << "利用无参构造函数创建的时间对象为:"; myClock_1.display();
Clock myClock_2(8, 3, 30); cout << "利用有参构造函数创建的时间对象为:"; myClock_2.display();
myClock_2.setHour(21); cout << "修改过的时间对象为:"; myClock_2.display(); system("pause"); return 0; }
|