为什么仅适用于C 的课堂上定义衍生类的构造方法
Why constructor for derived class can only be defined in-class for C++?
为什么我的代码下面的代码在complation :: base :: base()中投入汇编错误,而对派生和不良的reloc地址0x0的不确定引用'.ctors'.ctors'。但是,当我定义类派生的构造函数时,编译器可以编译代码。
#include <iostream>
class Base{
public:
Base();
virtual ~Base();
};
class Derived : public Base{
public:
Derived(double theob_);
virtual ~Derived();
private:
double theob;
};
Derived::Derived(double theob_):theob(theob_){}
int main(){
return 0;
}
您的编译单元声明 Base::Base()
,但没有定义它。您的派生构造函数在类外部的主体外被实现为非插入功能,因此将始终生成,并将引用编译单元中未包含的构造函数。如果将派生的构造函数包括在类描述中,则它将被内衬使用,并且如果实际调用它,则只有编译器才会为其生成代码。在您的情况下,这不是,因为您从不构造Derived
的实例。如果您实际构建了这样的实例,例如通过在main
中编写Derived d;
,您将遇到相同的问题。您可以使Base::Base
inline no-op:
class Base{
public:
Base() {}
virtual ~Base();
};
定义构造函数中的构造函数时,您会使构造函数成为内联方法。因此,在需要之前,它将不会实例化 - 即直到您没有声明类的变量。
尝试以下操作:
int main(){
Derived var(0.0);
return 0;
}
您会遇到同样的错误。
相关文章:
- 具有enable_if外部类原型的模板类构造函数定义
- 在方法定义中显式指定命名空间
- 没有针对完全专用模板类的外联虚拟方法定义
- 构造函数定义中类声明中的模板值
- 将虚拟方法定义为私有方法时会发生什么情况?
- C++中的继承和构造函数定义
- 单独的类声明和方法定义文件问题
- 如何使用模板化构造函数定义演绎指南?
- 构造函数定义C
- 不正确的成员构造函数定义
- Eclipse CDT 不了解方法定义是什么
- C++对象构造方法之间的差异
- C 方法定义具有模板
- Eclipse CDT将方法定义定义到标头文件
- 模板方法定义的问题 - 错误C2244:无法将函数定义与现有声明匹配
- 如何为 Product* getProductFromID(std::string)编写方法定义;.
- 具有虚拟多重继承的构造函数定义
- 为什么仅适用于C 的课堂上定义衍生类的构造方法
- 防止重新定义构造函数定义的方法
- 构造自定义编译库的更好方法