当前位置:主页 > 软件编程 > C代码 >

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

时间:2020-11-15 13:21:14 | 栏目:C代码 | 点击:

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

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(){}
   
};

结果为:

您可能感兴趣的文章:

相关文章