为什么仅适用于C 的课堂上定义衍生类的构造方法

Why constructor for derived class can only be defined in-class for C++?

本文关键字:构造方法 定义 课堂 适用于 为什么      更新时间:2023-10-16

为什么我的代码下面的代码在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;
}

您会遇到同样的错误。