【问题标题】:Passing Parameters to Base Class Constructors C++将参数传递给基类构造函数 C++
【发布时间】:2014-12-25 00:51:42
【问题描述】:

我喜欢在 C++ 中将我的类声明和定义分开。因此,在标题中,我可以定义一个“基”类,如下所示:

# Base.h
class Base 
{
    int n;    
public:
    Base(int x);
};

并在cpp文件中定义其构造函数实现,即,

# Base.c
Base::Base(int x) 
{
    n = x;
}

现在,如果我定义一个继承“基”类的“派生”类,我可以将参数传递给基类,如下所示:

#Derived.h
class Derived : public Base
{
    int t;
public:
    Derived(int y) : Base(t) {t = y;}
}

但是这样做需要我将 Derived 类的构造函数的主体放在头文件中,即{t = y;},因此构造函数定义不再与其声明分开。有没有办法将参数传递给类的基类构造函数,仍然使我能够在 cpp 文件中为派生类定义构造函数?

【问题讨论】:

    标签: c++ class inheritance constructor


    【解决方案1】:

    ,在头文件中:

    class Derived : public Base
    {
        int t;
    public:
        Derived(int y); // Declaration of constructor
    };
    

    在 cpp 文件中:

    Derived::Derived(int y) : Base(t) { // Definition of constructor
        t = y;
    }
    

    Member initializer lists 允许在类构造函数的定义中以及内联类内定义中。如果您有兴趣,我还建议您查看cppreference,了解有关初始化顺序和成员将在复合构造函数主体执行之前初始化这一事实的两个小警告。

    【讨论】:

      【解决方案2】:

      有没有办法将参数传递给类的基类构造函数,仍然使我能够在 cpp 文件中为派生类定义构造函数?

      当然有。标头可以只声明构造函数,就像您为 Base 所做的那样:

      class Derived : public Base
      {
          int t;
      public:
          Derived(int y);
      };
      

      然后你可以在源文件中实现它,就像你对Base 所做的那样:

      Derived::Derived(int y) : Base(y), t(y) {}
      

      请注意,您必须将参数y,而不是(尚未初始化的)成员t 传递给基本构造函数。基础子对象总是在成员之前初始化。

      【讨论】:

        猜你喜欢
        • 2023-04-04
        • 2015-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-06
        相关资源
        最近更新 更多