当前位置 : 主页 > 编程语言 > c语言 >

C++类继承 继承后函数的值实现详解

来源:互联网 收集:自由互联 发布时间:2021-05-12
类的继承会首先寻找基类,若基类未实现,则会寻找派生类的函数 1. class继承,函数不继承 #include stdio.h class Base{public: Base(){} ~Base(){} int a; void setA() { a = 1; }}; class A:public Base{public: A(){

类的继承会首先寻找基类,若基类未实现,则会寻找派生类的函数

1. class继承,函数不继承

#include <stdio.h>
 
class Base
{
public:
  Base(){}
  ~Base(){}
 
  int a;
  void setA()
  {
    a = 1;
  }
};
 
class A:public Base
{
public:
  A(){}
  ~A(){}
   
  void setA()
  {
    a = 2;
  }
   
};
 
class B:public Base
{
public:
  B(){}
  ~B(){}
   
  void setA()
  {
    a = 3;
  }
};
 
int main()
{
  A *ax = new A();
  B *bx = new B();
  Base *aClass = ax;
  Base *bClass = bx;
  aClass->setA();
  bClass->setA();
 
  printf("a value of a %d\n", aClass->a);
  printf("a value of b %d\n", bClass->a);
  return 0;
}

运行结果:

2. 函数和Class都继承

#include <stdio.h>
 
class Base
{
public:
  Base(){}
  ~Base(){}
 
  int a;
  virtual void setA()
  {
    a = 1;
  }
};
 
class A:public Base
{
public:
  A(){}
  ~A(){}
   
  virtual void setA()
  {
    a = 2;
  }
   
};
 
class B:public Base
{
public:
  B(){}
  ~B(){}
   
  virtual void setA()
  {
    a = 3;
  }
};
 
int main()
{
  A *ax = new A();
  B *bx = new B();
  Base *aClass = ax;
  Base *bClass = bx;
  aClass->setA();
  bClass->setA();
 
  printf("a value of a %d\n", aClass->a);
  printf("a value of b %d\n", bClass->a);
  return 0;
}

运行结果:注意派生类中可以不写virtual,最好写上,以辨别是函数继承

若将2中基类的函数写为纯虚函数,运行的结果一样,但是如果基类是纯虚函数,派生类必须实现相应的函数。

class Base
{
public:
  Base(){}
  ~Base(){}
 
  int a;
  virtual void setA()=0;
   
};

3. 类A中不有函数,则继承自基类

class A:public Base
{
public:
  A(){}
  ~A(){}
   
};

结果为:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自由互联。

网友评论