【C++第四課】---類的封裝

來源:互聯網
上載者:User

一、類的組成

一個類通常分為以下兩部分

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.


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.