如何分离派生 class 构造函数的定义和实现?

How to seperate definition and implementation of a derived class constructor?

我想了解如何在一个文件中定义派生的 class 构造函数,以便我可以在另一个文件中实现它。

public:
Derived(std::string name) : Base(name);
~Derived();

析构函数按预期工作,但是对于构造函数,我要么在末尾添加 {}(而不是分号),然后重新定义 'Derived' 错误,要么我被要求添加 {} 而不是分号.在这种情况下,分离定义和实现的方法是什么?

Base.h

#include <string>

class Base
{
protected:
    std::string name;
    ...
public:
    Base(std::string name);
    virtual ~Derived();
    ...
};

Base.cpp

#include "Base.h"

Base::Base(std::string name)
    : name(name)
{
    ...
}

Base::~Base()
{
    ...
}

Derived.h

#include "Base.h"

class Derived : public Base {
    ...
public:
    Derived(std::string name);
    ~Derived();
    ...
};

Derived.cpp

#include "Derived.h"

Derived::Derived(std::string name)
    : Base(name)
{
    ...
}

Derived::~Derived()
{
    ...
}

你可以像这样分开声明和定义:

class Derived : public Base {
public:
   Derived(std::string name); // declaration
   // ... other members here
};

然后,其他地方:

// definition
Derived::Derived(std::string name) : Base(name) {
  // ...
}

您可以按照与 class 的任何其他成员函数相同的方式进行操作。例如,

base.h

#pragma once 

#include <string>

class Base 
{
    std::string name;
    public:
        Base() = default;
        Base(std::string pname);//declaration
        //other members
};

base.cpp

#include "base.h"
#include <iostream>
//definition
Base::Base(std::string pname): name(pname)
{
    std::cout<<"Base constructor ran"<<std::endl;
    
}

derived.h

#pragma once
#include "base.h"
class Derived : public Base
{
  public: 
    Derived(std::string pname);//declaration
};

derived.cpp

#include "derived.h"
#include <iostream>
//definition
Derived::Derived(std::string pname): Base(pname)
{
    std::cout<<"Derived constructor ran"<<std::endl;
}

main.cpp


#include <iostream>
#include "derived.h"
#include "base.h"

int main()
{
    
    Derived d("anoop");
    return 0;
}