public private protected

一、先说类成员变量及成员函数的的属性。


1.public 与 private 的区别

这两个的区别学过C++的都比较清楚,public的变量和函数在类的内部外部都可以访问,而private只有在类的

内部可以访问

1. protected 与 private

如果一个类没有派生出其他类,那么protected和private是完全相同的,也就是说protected和private一样只

能在类的内部访问,不能在类的外部访问。

但是在派生其他类的情况下,protected和private的区别就体现出来了。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;//派生类可以访问基类的保护变量, 正确
}

// === 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; //类的外部不能访问保护变量, 错误
cout << "\nProgram " << argv[0] << endl << endl;

return EXIT_SUCCESS;
}
// ---------- end of function main ----------

  

编译:Makefile

all:main
main:main.cc
g
++ -g -Wall -O0 main.cc -o main

 

2.public 与 private 的区别

这两个的区别学过C++的都比较清楚,public的变量和函数在类的内部外部都可以访问,而private只有在类的

内部可以访问

 

#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;//类的内部可以访问私有变量, 正确
}
int Base::GetB()
{
return m_b;//类的内部可以访问公有变量, 正确
}

// === 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:main                                                                        
main:main.cc
g
++ -g -Wall -O0 main.cc -o main

  

posted @ 2011-07-22 21:52  wangkangluo1  阅读(596)  评论(0编辑  收藏  举报