您的位置:首页 > 编程语言 > C语言/C++

c++学习笔记(十一):C++类的访问修饰符

2016-07-21 18:01 841 查看
数据隐藏是面向对象编程的重要的特点,允许防止程序直接访问类类型的内部的功能之一。访问限制类成员被标记 public, private, 和protected 类主体部分。public, private, 和protected关键字被称为访问修辞符。

类可以有多个public, protected 或 private 标记部分。每个部分仍然有效,直至另一段标签或类主体的关闭右括号。会员和类的缺省访问是私有的。
class Base {

public:

// public members go here

protected:

// protected members go here

private:

// private members go here

};

公共成员:

公共成员可从该类以外的任何地方,设置和获取公共变量的值,而不作为显示在下面的实例的任何成员函数:#include <iostream> using namespace std; class Line { public: double length; void setLength( double len ); double getLength( void ); }; // Member functions definitions double Line::getLength(void) { return length ; } void Line::setLength( double len ) { length = len; } // Main function for the program int main( ) { Line line; // set line length line.setLength(6.0); cout << "Length of line : " << line.getLength() <<endl; // set line length without member function line.length = 10.0; // OK: because length is public cout << "Length of line : " << line.length <<endl; return 0; }
当上述代码被编译和执行时,它产生了以下结果:Length of line : 6
Length of line : 10

私有(private)成员:

私有成员变量或函数不能访问,甚至从类外面看。只有类和友元函数可以访问私有成员。默认情况下,类的所有成员将是私有的,例如在下面的类宽度为一个私有成员,这意味着直到标注一个成员,将假定一个私有成员:class Box
{
double width;
public:
double length;
void setWidth( double wid );
double getWidth( void );
};
实际上,我们在公有部分,以便它们可以从类的外部调用中所示的下列程序确定在专用段的数据和相关函数。#include <iostream>

using namespace std;

class Box
{
public:
double length;
void setWidth( double wid );
double getWidth( void );

private:
double width;
};

// Member functions definitions
double Box::getWidth(void)
{
return width ;
}

void Box::setWidth( double wid )
{
width = wid;
}

// Main function for the program
int main( )
{
Box box;

// set box length without member function
box.length = 10.0; // OK: because length is public
cout << "Length of box : " << box.length <<endl;

// set box width without member function
// box.width = 10.0; // Error: because width is private
box.setWidth(10.0); // Use member function to set it.
cout << "Width of box : " << box.getWidth() <<endl;

return 0;
}让我们编译和运行上面的程序,这将产生以下结果:Length of box : 10
Width of box : 10

保护(protected)成员:

保护成员变量或函数非常类似私有成员,但它提供了一个额外的好处,即它们可以在被称为派生类的子类进行访问。这里将学习派生类,继承在下一个章节。现在可以检查下面的例子中,我们已经从一个父类Box派生一个子类smallBox。下面的例子是类似于上述实例,这里宽度构件将通过其派生类在smallBox的任何成员函数访问。
#include <iostream>
using namespace std;

class Box
{
protected:
double width;
};

class SmallBox:Box // SmallBox is the derived class.
{
public:
void setSmallWidth( double wid );
double getSmallWidth( void );
};

// Member functions of child class
double SmallBox::getSmallWidth(void)
{
return width ;
}

void SmallBox::setSmallWidth( double wid )
{
width = wid;
}

// Main function for the program
int main( )
{
SmallBox box;

// set box width using member function
box.setSmallWidth(5.0);
cout << "Width of box : "<< box.getSmallWidth() << endl;

return 0;
}
让我们编译和运行上面的程序,这将产生以下结果:Width of box : 5

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: