【问题标题】:How to seperate definition and implementation of a derived class constructor?如何分离派生类构造函数的定义和实现?
【发布时间】:2022-01-11 20:58:00
【问题描述】:

我想学习如何在一个文件中定义派生类构造函数,以便我可以在另一个文件中实现它。

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

析构函数按预期工作,但是对于构造函数,我要么在末尾添加 {}(而不是分号),然后重新定义“派生”错误,要么要求我添加 {} 而不是分号。在这种情况下,有什么方法可以将定义和实现分开?

【问题讨论】:

  • : Base (name) 位是定义的一部分。如果你只是想要一个声明,那就是Derived(std::string name);
  • 我想你的意思是,“分开 declarationdefinition”。对于我们其他人来说,“定义”和“实现”是同一个东西,而“声明”代表了你不恰当地称为“定义”的无实现的东西。

标签: c++ oop inheritance constructor derived-class


【解决方案1】:

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()
{
    ...
}

派生的.h

#include "Base.h"

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

派生的.cpp

#include "Derived.h"

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

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

【讨论】:

  • 基本析构函数是虚拟的有什么好处?
  • @VytautasK See here。因此,如果您通过调用 delete foo; 删除 Derived 对象,其中 fooBase* 指针,其指向的对象是 Derived 实例,一切正常。
【解决方案2】:

您的操作方式与类的任何其他成员函数相同。例如,

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;
    
}

派生的.h

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

派生的.cpp

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

ma​​in.cpp


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

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

【讨论】:

    【解决方案3】:

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

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

    然后,在别处:

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

    【讨论】:

      猜你喜欢
      • 2021-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-02
      • 2016-12-20
      • 1970-01-01
      • 2011-09-27
      相关资源
      最近更新 更多