zoukankan      html  css  js  c++  java
  • c++中的成员选择符

    c++中支持仅能指向类成员的指针,对这种类型的指针进行数据的提取操作时,可使用如下两种类型的操作符:成员对象选择操作符.* 和 成员指针选择操作符->*

    例一:

     1 #include <iostream>
     2 using namespace std;
     3 struct C
     4 {
     5     int x;
     6     float y;
     7     float z;
     8 };
     9 int main()
    10 {
    11     float f;
    12     int* i_ptr;
    13 
    14     C c1, c2;
    15 
    16     float C::*f_ptr; // a pointer to a float member of C
    17     f_ptr = &C::y;  //point to C member y
    18     c1.*f_ptr = 3.14; // set c1.y = 3.14
    19     c2.*f_ptr = 2.01; // set c2.y = 2.01
    20 
    21     f_ptr = &C::z;  // point to C member z
    22     c1.*f_ptr = -9999.99; //set c1.z = -9999.99
    23 
    24     f_ptr = &C::y; //point to C member y
    25     c1.*f_ptr = -777.77; // set c1.y
    26 
    27     f_ptr = &C::x; // ****Error: x is not float****
    28 
    29     f_ptr = &f; // ****Error: f is not a float member of C****
    30 
    31     i_ptr = &c1.x; //c1.x is an int
    32 
    33     //...
    34 
    35     return 0;
    36 }

    例二:定义和使用指向成员函数的指针

     1 #include <iostream>
     2 using namespace std;
     3 
     4 struct C
     5 {
     6     int x;
     7     short f(int){//....};
     8     short g(int){//....};
     9 };
    10 
    11 int main()
    12 {
    13     short s;
    14     C c;
    15     short (C::*meth_ptr) (int);
    16     meth_ptr = &C::f;
    17 
    18     s = (c.*meth_ptr)(8);
    19     C* ptr = &c;
    20     s = (ptr->*meth_ptr)(9);
    21     meth_ptr = &C::g;
    22     s = (c.*meth_ptr)(10);
    23     s = (ptr->*meth_ptr)(11);
    24     return 0;
    25 }
  • 相关阅读:
    如何培养编程所需要的逻辑思维?
    CSS教程
    Android中Service(服务)详解
    Tomcat热部署的实现原理
    Java多线程和线程池(转)
    导出Excel表格
    各种时间格式化的转化
    上传多媒体文件到微信公众平台
    发起https请求并获取结果
    Java 将字节转换为十六进制字符串
  • 原文地址:https://www.cnblogs.com/xlzhh/p/4448110.html
Copyright © 2011-2022 走看看