问题:经过不停的改进,结构体 struct 变得越来越不像它在 C 语言中的样子了!!类的关键字strut 在 C 语言中已经有了自己的含义,必须继续兼容在 C++ 中提供了新的关键字 class 用于类定义class 和 strut 的用法是完全相同的class 和 struct 有什么区别呢?在用 struct 定义类时,所有成员的默认访问级别为 public在用 class 定义类时,所有成员的默认访问级别为 privatestruct A{ // default to public int i; // default to public int getI() { return i; }};class B{ // default to private int i; // default to private int getI() { return i; }};良好的编程习惯:显示的声明每个成员的访问级别编程实验: class的初探test_1.cpp#include <stdio.h>struct A{ // default to public int i; // default to public int getI() { return i; }};int main(){ A a; a.i = 4; printf(“a.getI() = %d\n”, a.getI()); return 0;}输出:a.getI() = 4test_2.cpp#include <stdio.h>class B{ // default to private int i; // default to private int getI() { return i; }};int main(){ B b; b.i = 4; printf(“b.getI() = %d\n”, b.getI()); return 0;}输出:main.cpp: In function ‘int main()’:main.cpp:6: error: ‘int B::i’ is privatemain.cpp:18: error: within this contextmain.cpp:8: error: ‘int B::getI()’ is privatemain.cpp:20: error: within this context小实例需求: 开发一个用于四则运算的类提供 setOperator 函数设置运算类型提供 setParameter 函数设置运算数提供 result 函数进行运算其返回值表示运算的合法性通过引用参数返回结果C++ 中的类支持声明和实现的分离将类的实现和定义分开.h 头文件中只有类声明成员变量和成员函数的声明.cpp 源文件中完成类的其它实现成员函数的具体实现实例分析: Operator 类的分析用户需求描述:Operator.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功能实现: Operator.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 0;}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(“Calculator error!\n”); } return 0;}输出:r = 3.000000小结C++ 引入了新的关键字 class 用于定义类struct 和 class 的区别在于默认访问级别的不同C++ 中的类支持声明和实现的分离在头文件中声明类在源文件中实现类以上内容参考狄泰软件学院系列课程,请大家保护原创!