标签:auto col int result height 分享 头文件 info als
经过不停的改进,结构体struct变得越来越不像它在C语言中的样子了。
类的关键字:
类的关键字:
示例程序:
1 #include <stdio.h> 2 3 struct A 4 { 5 // defualt to public 6 int i; 7 // defualt to public 8 int getI() 9 { 10 return i; 11 } 12 }; 13 14 class B 15 { 16 // defualt to private 17 int i; 18 // defualt to private 19 int getI() 20 { 21 return i; 22 } 23 }; 24 25 int main() 26 { 27 A a; 28 B b; 29 30 a.i = 4; 31 32 printf("a.getI() = %d\n", a.getI()); 33 34 b.i = 4; 35 36 printf("b.getI() = %d\n", b.getI()); 37 38 return 0; 39 }
34、36行是错误的,不能访问private级别的成员。
小实例:
类的真正形态:
头文件如下:
1 #ifndef _OPERATOR_H_ 2 #define _OPERATOR_H_ 3 4 class Operator 5 { 6 private: 7 char mOp; 8 double mP1; 9 double mP2; 10 11 public: 12 bool setOperator(char op); 13 void setParameter(double p1, double p2); 14 bool result(double& r); 15 }; 16 17 #endif
源文件如下:
1 #include "Operator.h" 2 3 bool Operator::setOperator(char op) 4 { 5 bool ret = false; 6 7 if( (op == ‘+‘) || (op == ‘-‘) || (op == ‘*‘) || (op == ‘/‘) ) 8 { 9 ret = true; 10 mOp = op; 11 } 12 else 13 { 14 mOp = ‘\0‘; 15 } 16 17 return ret; 18 } 19 20 void Operator::setParameter(double p1, double p2) 21 { 22 mP1 = p1; 23 mP2 = p2; 24 } 25 26 bool Operator::result(double& r) 27 { 28 bool ret = true; 29 30 switch( mOp ) 31 { 32 case ‘/‘: 33 if( (-0.000000001 < mP2) && (mP2 < 0.000000001) ) 34 { 35 ret = false; 36 } 37 else 38 { 39 r = mP1 / mP2; 40 } 41 break; 42 case ‘+‘: 43 r = mP1 + mP2; 44 break; 45 case ‘*‘: 46 r = mP1 * mP2; 47 break; 48 case ‘-‘: 49 r = mP1 - mP2; 50 break; 51 default: 52 ret = false; 53 break; 54 } 55 56 return ret; 57 }
测试程序:
1 #include <stdio.h> 2 #include "Operator.h" 3 4 int main() 5 { 6 Operator op; 7 double r = 0; 8 9 op.setOperator(‘/‘); 10 op.setParameter(9, 3); 11 12 if( op.result(r) ) 13 { 14 printf("r = %lf\n", r); 15 } 16 else 17 { 18 printf("Calculate error!\n"); 19 } 20 21 return 0; 22 }
运算结果如下:
小结:
标签:auto col int result height 分享 头文件 info als
原文地址:https://www.cnblogs.com/wanmeishenghuo/p/9568536.html