C++继承和构造函数、析构函数
C++ inheritance and constructors, destructors
//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
$
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 在c++中使用向量时,如何调用构造函数和析构函数
- 为什么在使用转换构造函数赋值后调用C++类的析构函数?
- 不命名构造函数和析构函数上的类型错误
- 在 UML 类图中为C++类添加构造函数和析构函数
- 基类中的默认析构函数禁用子类中的移动构造函数(如果有成员)
- 为什么类构造函数为其成员生成析构函数?
- makefile对我的名称空间对象/函数/构造函数的不确定引用
- 没有可调用的匹配函数(构造函数),候选函数不同于对给定类型的引用
- C++库制作,隐藏在标头中没有友元的析构函数/构造函数
- 从另一个成员函数/构造函数调用C++构造函数是否执行初始值设定项列表
- 在另一个函数/构造函数 [C++] 中初始化后使变量只读
- std::调用函数时找不到函数构造函数
- 显式调用基类析构函数/构造函数合法吗
- 函数构造函数和nullptr
- 用委托构造函数构造函数
- 虚函数构造函数和调用虚函数时会发生什么
- 一些Qt函数/构造函数参数的内存管理
- 使用for_each或std::transform时,c++函函数构造函数是如何被调用的?
- std函数构造函数初始化