现在的位置: 首页 > 综合 > 正文

父类 子类

2012年10月07日 ⁄ 综合 ⁄ 共 1522字 ⁄ 字号 评论关闭

 如果一个派生类的派生符是public 则 ,将基类称为 父类,派生类称为子类,

C++ 允许,父类的指针直接指向子类的对象,或者父类引用子类:

 

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
class point{
     int x;
     int y;
     public:
     point(int x,int y):x(x),y(y){}
   void  show(){ cout<<"point"<<endl;}
     };
class circle:public point{
     int r;
     public:
     void show(){ cout<<"circle"<<endl;}
     circle(int x,int y,int r):point(x,y),r(r){}
     };
int main()
{
     circle c(1,2,3);
     point * p=&c;
     c.show();
     p->show();
     system("pause");
     return 0;
     }

 

 如果一个函数被声明为基类的友元,则该友元内部的基类指针,也可以指向派生类的对象,即

 对于基类的友元而言,在友元内部,基类被当做父类。

 

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
class point{
     int x;
     int y;
     public:
     point(int x,int y):x(x),y(y){}
     void  show(){ cout<<"point"<<endl;}
     friend void f1();
     void f2();
     };
class circle:point{
     int r;
     public:
     void show(){ cout<<"circle"<<endl;}
     circle(int x,int y,int r):point(x,y),r(r){}
     };
circle c(1,2,3);
void f1()
{
    point *p=&c;
    p->show();
}

/*void f2()
{
    point *p=&c;//f2不能访问
    p->show();
}  */
int main()
{

     f1();
     //f2(); f2不能访问
system("pause"); return 0; }

 

做个补充:父子类可以做下面这四件事(和上面的第一个冲突):

 1:子类的对象可以给父类赋值。 赋值效果,基类数据成员和派生类中数据成员的值相同

 2:子类的对象可以初始化父类的引用

 3:父类的指针可以指向子类的地址

 4:函数的参数是父类的引用时,当函数调用时,可以将子类的对象作为实参

 

  

#include<iostream>
#include<stdio.h>
#include<string>
#include<stdlib.h>
using namespace std;
class base{
    string name;
    public:
    void show();
    base(string name):name(name){}
};
void base::show()
{
    cout<<"base->"<<base::name<<endl;
}
class son:public base{
     public:
     void show();
     son(string name):base(name){}
};
void son::show()
{
    cout<<"son"<<endl;
}
void f(base & fa)
{
     fa.show();
}
int main()
{
    son a("guo");
    a.show();
    base b(a);
    b.show();
    //son c(b);


    base & c=a;
    c.show();


    base * d=&a;
    d->show();

    f(a);
    system("pause");
}

 

抱歉!评论已关闭.