public private protected
生活随笔
收集整理的這篇文章主要介紹了
public private protected
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一、先說類成員變量及成員函數(shù)的的屬性。
1.public 與 private 的區(qū)別
這兩個的區(qū)別學(xué)過C++的都比較清楚,public的變量和函數(shù)在類的內(nèi)部外部都可以訪問,而private只有在類的
內(nèi)部可以訪問
1. protected 與 private
如果一個類沒有派生出其他類,那么protected和private是完全相同的,也就是說protected和private一樣只
能在類的內(nèi)部訪問,不能在類的外部訪問。
但是在派生其他類的情況下,protected和private的區(qū)別就體現(xiàn)出來了。private型變量只能在類本身中訪問,
在其派生類中也不能訪問;而protected型的變量可以在派生類中訪問
/** =====================================================================================
*
* Filename: main.cc
*
* Description:
*
* Version: 1.0
* Created: 07/22/2011 09:41:51 PM
* Revision: none
* Compiler: gcc
*
* Author: kangle.wang (mn), wangkangluo1@gmail.com
* Company: APE-TECH
*
* =====================================================================================
*/
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
using namespace std;
class Base
{
public:
Base(int a, int b = 0);
protected:
int m_b;
private:
int m_a;
};
class Derive : public Base
{
public:
Derive(int a, int b = 0) : Base(a, b) {}
int GetA();
int GetB();
};
Base::Base(int a, int b)
{
m_a = a;
m_b = b;
}
int Derive::GetA()
{
return 1;
//return m_a;//派生類不能訪問基類的私有變量, 錯誤
}
int Derive::GetB()
{
return m_b;//派生類可以訪問基類的保護(hù)變量, 正確
}
// === FUNCTION ======================================================================
// Name: main
// Description: main function
// =====================================================================================
int
main ( int argc, char *argv[] )
{
int num = 0;
Base b(10, 20);
//num = b.m_a; //類的外部不能訪問私有變量, 錯誤
//num = b.m_b; //類的外部不能訪問保護(hù)變量, 錯誤
cout << "\nProgram " << argv[0] << endl << endl;
return EXIT_SUCCESS;
} // ---------- end of function main ----------
編譯:Makefile
all:mainmain:main.cc
g++ -g -Wall -O0 main.cc -o main
2.public 與 private 的區(qū)別
這兩個的區(qū)別學(xué)過C++的都比較清楚,public的變量和函數(shù)在類的內(nèi)部外部都可以訪問,而private只有在類的
內(nèi)部可以訪問
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
using namespace std;
class Base
{
public:
Base(int a, int b = 0);
int GetA();
int m_b;
private:
int GetB();
int m_a;
};
Base::Base(int a, int b)
{
m_a = a;
m_b = b;
}
int Base::GetA()
{
return m_a;//類的內(nèi)部可以訪問私有變量, 正確
}
int Base::GetB()
{
return m_b;//類的內(nèi)部可以訪問公有變量, 正確
}
// === FUNCTION ======================================================================
// Name: main
// Description: main function
// =====================================================================================
int
main ( int argc, char *argv[] )
{
int num;
Base b(10);
// num = b.m_a; //類的外部不能訪問私有變量, 錯誤
num = b.m_b;//類的外部可以訪問公有變量, 正確
cout << "\nProgram " << argv[0] << endl << endl;
return EXIT_SUCCESS;
} // ---------- end of function main ----------
編譯:Makefile
all:mainmain:main.cc
g++ -g -Wall -O0 main.cc -o main
完
總結(jié)
以上是生活随笔為你收集整理的public private protected的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 通过GetProcAddress函数动态
- 下一篇: java知识点--基础篇(5)