类与封装形态
Posted 阿弥陀佛.a
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了类与封装形态相关的知识,希望对你有一定的参考价值。
一个类可以有很多对象,而一个对象必然属于某个类
#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); // i = 2;
printf("::i = %d\\n", ::i); // ::i = 1;默认命名空间的i
// printf("test.i = %d\\n", test.i); // Error
printf("test.j = %d\\n", test.j); // test.j = 4
printf("test.getI() = %d\\n", test.getI()); // test.getI() = 3
return 0;
}
//.h
#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
//.cpp
#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;
}
//main.cpp
#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;
}
以上是关于类与封装形态的主要内容,如果未能解决你的问题,请参考以下文章
VSCode自定义代码片段14——Vue的axios网络请求封装
VSCode自定义代码片段14——Vue的axios网络请求封装