-
类的关键字
- struct定义类时,所有成员默认访问级别为public
- class定义类时,所以成员默认访问级别为private
-
工程设计主要分为
- 类的声明和实现分离
- 声明放头文件
- 实现放源文件
#ifndef _OPERATOR_H_
#define _OPERATOR_H_
class Operator
{
private:
char mOp;
double mP1;
double mP2;
public:
bool setOperator(char op);
void setParameter(double p1, double p2);
bool result(double& r);
};
#endif
#include "Operator.h"
bool Operator::setOperator(char op)
{
bool ret = false;
if( (op == '+') || (op == '-') || (op == '*') || (op == '/') )
{
ret = true;
mOp = op;
}
else
{
mOp = '\0';
}
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.000000001 < mP2) && (mP2 < 0.000000001) )
{
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;
}
#include <stdio.h>
#include "Operator.h"
int main()
{
Operator op;
double r = 0;
op.setOperator('/');
op.setParameter(9, 3);
if( op.result(r) )
{
printf("r = %lf\n", r);
}
else
{
printf("Calculate error!\n");
}
return 0;
}