当前位置:   article > 正文

【C++】类作用域详解_c++ 作用域::

c++ 作用域::

目录

1. 可以在不同类中使用相同的类成员名

2. 不能从外部访问类成员,公有成员函数如此,要调用公有成员函数,必须通过对象

3. 定义成员函数时必须使用作用域解析运算符

4. 使用成员运算符(.)、简介成员运算符(->)或作用解析运算符(::)

5.  作用域为类的常量

5.1 第一种方式是在类中声明一个枚举

5.2 第二种方式是使用关键字static:

6 作用域内枚举

C++11提供一种新的枚举, class 或者 struct


 

在类定义中的 名称作用域都为整个类,作用域为 整个类值在该类是已知的

1. 可以在不同类中使用相同的类成员

  1. class Stock {
  2. public:
  3. int memi;
  4. double memd;
  5. };
  6. class Jodbj {
  7. public:
  8. int memi;
  9. double memd;
  10. };

2. 不能从外部访问类成员,公有成员函数如此,要调用公有成员函数,必须通过对象

Stock sleeper(........);

sleeper.show();

show();//这是错的!

3. 定义成员函数时必须使用作用域解析运算符

  1. void Stock::update(double price)
  2. {
  3. ...
  4. }

4. 使用成员运算符(.)、简介成员运算符(->)或作用解析运算符(::)

  1. Class obj; // Class is some class type
  2. Class *ptr = &obj;
  3. // member is a data member of that class
  4. ptr->member; // fetches member from the object to which ptr points
  5. obj.member; // fetches member from the object named obj
  6. // memfcn is a function member of that class
  7. ptr->memfcn(); // runs memfcn on the object to which ptr points
  8. obj.memfcn(); // runs memfcn on the object named obj

5.  作用域为类的常量

这样是错误的:

  1. class Bakery
  2. {
  3. private:
  4. const int Months = 12;
  5. double const[Months];
  6. }

声明类只是描述了对象的形式,并没有创建对象

在创建对象前,将没有用于存储值得空间。

5.1 第一种方式是在类中声明一个枚举

  1. class Bakery
  2. {
  3. private:
  4. enum { Months =12 };
  5. double const[Months];
  6. }

这种声明枚举并不会创建类数据成员,也就是所有对象中都不包含枚举。

Months只是一个符号名称,在作用域遇到时自动替换。

5.2 第二种方式是使用关键字static:

  1. calss Bakery
  2. {
  3. private:
  4. static const int Months =12;
  5. double costs[Months];
  6. }

这将创建一个名为Months的常量,该常量将于其他静态变量存储在一起,而不是存储在对象中。

6 作用域内枚举

两个枚举定义中的枚举量可能会发生冲突

enum egg {big,  small, large};

enum shirt {big, small, large};

上面无法编译,因为在相同作用域,发生问题

C++11提供一种新的枚举, class 或者 struct

enum class egg{big,  small, large};

enum class shirt{big,  small, large};

如何使用?

egg choice = egg::large;

shirt FLUO= shirt::large;

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/blog/article/detail/51658
推荐阅读
相关标签
  

闽ICP备14008679号