一、類的組成
一個類通常分為以下兩部分
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; }
//關於.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.