【C++第四课】---类的封装

一、类的组成

一个类通常分为以下两部分

1、类的实现细节(只有在创建类得时候才关心)

2、类得使用方式(只有在使用类得时候才关心)


二、C++中类的封装

1、成员变量(C++中表示类属性的变量)

2、成员函数(C++中表示类型行为的函数)

在C++中使用如下关键字来指定成员变量和成员函数的访问访问级别

public
- 成员变量和成员函数可以在类的内部和外界访问和调用


- private
- 成员变量和成员函数只能在类的内部被访问和调用

三、struct和class的一个区别

注意struct的用法只为了兼容C 的写法 struc定义的类,默认的成员是public的

而class定义的类默认的成员是private的。


四、一个关于类的例子----运算类得编写

Operate.cpp

#include "Operator.h"

bool Operator::SetOperator(char OP)
{
	bool ret = -1;
	if( OP == ('+') || OP == ('-') || OP == ('*') || OP == ('/') )
	{
		m_OP = OP;
		ret = 0;	
	}
	return ret;	
}
bool Operator::SetParameter(double PA1,double PA2)
{
	bool ret = -1;
	
	if( (PA2 < 0.00000001) && (PA2 > -0.00000001) )
	{
		ret = -1;
	}
	else
	{
		m_PA1 = PA1;
		m_PA2 = PA2;	
		ret = 0;		
	}
	return ret;
}
double Operator::result(void)
{
	double ret = 0;
	switch(m_OP)
	{
		case '+':
			ret = m_PA1 + m_PA2;break;
		case '-':
			ret = m_PA1 - m_PA2;break;
		case '*':
			ret = m_PA1 * m_PA2;break;
		case '/':
			ret = m_PA1 / m_PA2;break;
		default:
			break;
	}
	return ret;
}


Operator.h

#ifndef __OPERATOR_H_
#define __OPERATOR_H_

class Operator
{
private:
 	char m_OP;
 	double m_PA1;
 	double m_PA2;
 		
public:
 	bool SetOperator(char OP);
	bool SetParameter(double PA1,double PA2);
	double result(void);
};

#endif


main.c

 #include <iostream>
 #include "Operator.h"
 
 using namespace std;
 
 int main(int argc,char** argv)
 {
 	Operator operator2;
 	
 	operator2.SetOperator('-');
 	operator2.SetParameter(1,100);
 	int ret = operator2.result();
 	cout<<"the result is "<<ret<<endl;
 	return 0;
 }
 

注意了,注意了,在linux中的g++编译器中编译后,一直会产生如下错误,未定义???怎么可能????


通过查阅发现,是这个问题:

之前一版本我用命令行编译了 operator.h 生成了operator.h.gch这个文件,因为存在这个文件所以编译器并不会调用我更新后的头文件

直接删除就好了

//关于.h.gch
 A '.gch' file is a precompiled header.


if a '.gch' is not found then the normal header files will be used.


However, if your project is set to generate precompiled headers it will make them if they don’t exist and use them in the next build.


Sometimes the *.h.gch will get currupted or contain outdate information, so deleteing that file and compiling it again should fix it.


最后就是这样


结果没有任何问题的。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值