首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

问一个子类访问父类私有成员变量的有关问题

2012-03-30 
问一个子类访问父类私有成员变量的问题我看到一本 C++编程--从问题分析到程序设计 ,里面讲子类可以

问一个子类访问父类私有成员变量的问题
我看到一本 < <C++编程--从问题分析到程序设计> > ,里面讲子类可以
继承父类所有的成员变量和函数,虽然子类能继承父类的私有成员
变量,但是不能直接访问父类的私有成员变量,但是可以通过父类的
public类型的成员函数来访问父类的私有成员变量
比如
class   BaseClass
{
private   :
    int   u;
    int   v;
public:
    void   display();
};
void   BaseClass:display()
{
    cout < < "u= " < <u < < ",v= " < <v < <endl;
}
class   SubClass:public   BaseClass
{
        private:
            int   x;
            int   y;
        public:
                void   display();
};
void   SubClass:display()
{
        BaseClass::display();
        cout < < "x= " < <x < < ",y= " < <y < <endl;
}
我省略了构造函数,这个例子表明子类SubClass可以通过display
来访问父类的私有成员变量u,v
那么,我自己又写了下面的程序,为什么永远都是打印出-1   ?

#include <iostream>
using   namespace   std;
class   person
{
private:
int   age;
public:
person();
person(int   age);
void   display();
};
void   person::display()
{
cout < < "In   Base   Class,age= " < <age < <endl;
}
person::person()
{
this-> age=-1;
        cout < < "Default   constructor " < <endl;
}
person::person(int   age)
{
this-> age=age;
cout < < "Argument " < <endl;
}
class   student:public   person
{
public:
student(int   b)
{
person::person(b);
}
void   display();

};
void   student::display()
{
person::display();
cout < < "sub   class   display " < <endl;
}
void   main()
{

student   a(10);
a.display();
}

[解决办法]
student(int b)
{
person::person(b);
}

错了:
student(int b) :person(b)
{
}
[解决办法]
person::person(b);
不能这样调用构造函数。 你看一下反汇编跟踪一下两次调用person构造函数(第一次调用了不带参数的,第二次应该就是你写的person::person(b);) 比较一下 Age地址就会发现两次赋值的地址是不同的.
[解决办法]
class person
{
private:
int age;
public:
person();
~person();
person(int age);
void display();
};
void person::display()
{
cout < < "In Base Class,age= " < <age < <endl;
}
person::person()
{
this-> age=-1;
cout < < "Default constructor " < <endl;
}
person::~person()
{
cout < < "In Base Class,age= " < <age < <endl;
cout < < " deconstructor " < <endl;
}
person::person(int age)
{
this-> age=age;
cout < < "Argument " < <endl;
}
class student:public person
{
public:
student(int b)//这里相当于student(int b) :person()是调用无参数构造函数
{
person::person(b);
}
void display();



};
void student::display()
{
person::display();
cout < < "sub class display " < <endl;
}
void main()
{

student a(10);//这里初始化的是基类的person()构造函数
a.display();//
}

我帮你加了析构函数为了让你更清楚的了解到时调用了哪些函数!
运行结果为:
Default constructor
Argument //注意这里是调用student(int b)函数里的person::person(b)
In Base Class,age=10//析构person(b)
deconstructor
In Base Class,age=-1
sub class display
In Base Class,age=-1
deconstructor

当基类中声明有默认形式的构造函数或未声明构造函数时,派生类构造函数可以不向基类构造函数传递参数。
若基类中未声明构造函数,派生类中也可以不声明,全采用默认形式构造函数。
当基类声明有带形参的构造函数时,派生类也应声明带形参的构造函数,并将参数传递给基类构造函数。

热点排行