C++类中的封装-9
一。類通常分為以下兩個部分
1.類的實現細節
2.類的使用方式
二。C++中類的封裝
1.成員變量
c++中用于表示類屬性的變量
2.成員函數
c++中用于表示類的行為的函數
3.在C++中可以給成員變量和成員函數定義訪問級別
-public
成員變量和成員函數可以在類的內部和外界訪問和調用
-private
成員變量和成員函數智能在類的內部被訪問和調用
#include <stdio.h>struct Biology {bool living; };struct Animal : Biology {bool movable;void findFood() { } };struct Plant : Biology {bool growable; };struct Beast : Animal {void sleep(){ } };struct Human : Animal {void sleep() {printf("I'm sleeping...\n");}void work(){printf("I'm working...\n");} };struct Girl : Human { private:int age;public:void play(){printf("I'm girl, I'm playing...\n");}void print(){age = 22;printf("Girl's age is %d\n", age);play();sleep();work();} };struct Boy : Human { public:int age;void play(){printf("I'm boy, I'm playing...\n");}void print(){age = 23;printf("Boy's age is %d\n", age);play();sleep();work();} };int main(int argc, char *argv[]) {Girl girl;girl.print();Boy boy;boy.print();printf("Press any key to continue...");getchar();return 0; }4.類成員的作用域都只在類的內部,外部無法直接訪問
成員函數可以直接訪問成員變量和調用其他成員函數
5.類的外部可以通過類變量訪問public成員
類成員的作用域與訪問級別沒有關系
6.c++中用struct定義的類的所有成員默認為public。
用Class定義的類的所有成員都默認為private
三。類的作用域
#include <stdio.h>int i = 1;struct Test { private:int i;public:int j;int getI(){i = 3;return i;} };int main() {int i = 2;Test test;test.j = 4;printf("i = %d\n", i);printf("::i = %d\n", ::i);// printf("test.i = %d\n", test.i);printf("test.j = %d\n", test.j);printf("test.getI() = %d\n", test.getI());printf("Press any key to continue...");getchar();return 0; }輸出結果 2 1 4 3?
四。一個運算類的實現:
1. 提供 setOperator 函數設置運算類型,如加、減、乘、除。
2.提供 setParameter 函數設置運算參數,類型為整型。
3.提供 result 函數進行運算,其返回值表示運算的合法性,通過引用參數返回結果。
operator.c
#include"operate.h"bool Operator::setOperator(char op) {bool ret = false;if( (op == '+')||(op == '-')||(op == '*')||(op == '/') ){ret = true; mOp = op;}return ret; } void Operator::setParameter(double p1, double p2) {mP1 = p1;mP2 = p2; } bool Operator::result(double& r) {bool ret = true;switch(mOp){case '/':if((-0.000001 < mP2) && (mP2 <0.0000001)){ret = false; } else {r = mP1 / mP2; }break;case '+':r = mP1 + mP2; break;case '-':r = mP1 - mP2; break;case '*':r = mP1 * mP2; break;default:ret = false;break; } return ret; }operator.h
#ifndef _OPERATE_H_ #define _OPERATE_H_class Operator {public:bool setOperator(char op);void setParameter(double p1, double p2);bool result(double& r);private: char mOp;double mP1;double mP2;};#endifmain.c
#include <stdio.h> #include"operate.h"int main(int argc, char *argv[]) {Operator op;double r = 0;op.setOperator('/');op.setParameter(6,0);if( op.result(r) ){printf("Result is %f\n",r); }printf("Press any key to continue...");getchar();return 0; }轉載于:https://www.cnblogs.com/lvxiaoning/p/7591807.html
總結
以上是生活随笔為你收集整理的C++类中的封装-9的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 作业精灵怎么拍照
- 下一篇: 方舟烹饪锅怎么用 方舟生存进化