C++继承和构造函数、析构函数

C++ inheritance and constructors, destructors

本文关键字:析构函数 构造函数 继承 C++      更新时间:2023-10-16
//Parent.h
class Parent{
public:
   Parent(){}
   ~Parent(){}
   virtual void func1() = 0;
};
//Child.h
#include "Parent.h"
class Child : public Parent{
  int x, y;
public:
  Child() : Parent(){ //constructor
  }
  virtual void func1();
};
//Child.cpp
#include "Child.h"
void Child::Parent::func1(){
}

这编译得很好,但是,我想将 Child 类的构造函数(和析构函数)的实现放在其 cpp 文件中,可以吗?如何?

我已经尝试了下面的代码,但它为孩子抛出了对 vtable 的未定义引用

Child::Child() : Parent(){  //in the cpp
}
Child(); //in the header file 
Child():Parent(); //also tried this one

有几件事要做:

  • 保护发布头文件以防止意外的多重包含。
  • 使父析构函数成为虚拟
  • 初始化非自动成员变量以确定值。

您的最终布局可能如下所示。

家长.h

#ifndef PARENT_H_
#define PARENT_H_
class Parent
{
public:
    Parent() {};
    virtual ~Parent() {};
public:
    virtual void func1() = 0;
};
#endif // PARENT_H_

儿童.h

#ifndef CHILD_H_
#define CHILD_H_
#include "Parent.h"
class Child : public Parent
{
    int x,y;
public:
    Child();
    virtual ~Child();
    virtual void func1();
};
#endif

孩子.cpp

Child::Child()
   : Parent()     // optional if default
   , x(0), y(0)   // always initialize members to determinate values
{
}
Child::~Child()
{
}
void Child::func1()
{
}
$ cat Parent.h 
#ifndef GUARD_PARENT_H_
#define GUARD_PARENT_H_
class Parent{
public:
   Parent(){}
   ~Parent(){}
   virtual void func1() = 0;
};
#endif /* GUARD_PARENT_H_ */
$ cat Child.h
#ifndef GUARD_CHILD_H_
#define GUARD_CHILD_H_
#include "Parent.h"
class Child : public Parent{
  int x, y;
public:
  Child();
  virtual void func1();
};
#endif /* GUARD_CHILD_H_ */
$ cat Child.cpp
#include "Child.h"
Child::Child() : Parent() {
}
void Child::func1(){
}
$ cat try.cc
#include "Child.h"
int main() {
        Child c;
}
$ g++ try.cc Child.cpp
$ ./a.out
$