c++访问声明有关猜测

c++访问声明:
访问声明的方法就是直接把基类中的保护成员或公有成员 写在私有派生类定义式中的同名段同,同时给成员名前冠以基类名和作用域标识符"::"。
如下面的例子:

View Code
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
class A{
  public:
    A(int x1){x = x1;}
    void show(){cout<<"x="<<x<<endl;}
  //  void show(int y){cout<<"y="<<y<<endl;}
    private:
        int x;
};

class B: private A{
    public:
        B(int x1,int y1):A(x1){y=y1;}
        A::show;
    private:
        int y;
};

int main()
{
    B b(10,20);
    b.show();
    //b.show(10);
    return 0;
}

 


访问声明只含不带类型和参数的函数名或变量名。
所以下面的都是错的:
void A::show;

A::show();

void A::show();

个人觉得这和c++的重载性有关,如果类A中重载了show函数,如果写成上面三种错误的方式,将会要写很多次。但如果只写成A::show;就一次性
把所有的同名函数都从类A中弄过来了,简单而高效。如下面:

#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
class A{
  public:
    A(int x1){x = x1;}
    void show(){cout<<"x="<<x<<endl;}
    void show(int y){cout<<"y="<<y<<endl;}
    private:
        int x;
};

class B: private A{
    public:
        B(int x1,int y1):A(x1){y=y1;}
        A::show;
    private:
        int y;
};

int main()
{
    B b(10,20);
    b.show();
    b.show(10);
    return 0;
}

posted on 2012-10-28 19:08  aigoruan  阅读(215)  评论(0)    收藏  举报

导航