簡體   English   中英

隱式地將參數傳遞給基礎構造函數C ++

[英]Implicitly passing parameter(s) to base constructor C++

我對這里提出的完全相同的問題感興趣,但對於C ++。 有沒有辦法隱式地將參數傳遞給基類構造函數 這是我嘗試過的一個小例子,它不起作用。 當我刪除注釋並顯式調用基類構造函數時 ,一切正常。

struct Time { int day; int month; };
class Base {
public:
    Time time;
    Base(Time *in_time)
    {
        time.day   = in_time->day;
        time.month = in_time->month;
    }
};
class Derived : public Base {
public:
    int hour;
    // Derived(Time *t) : Base(t) {}
};
int main(int argc, char **argv)
{
    Time t = {30,7};
    Derived d(&t);
    return 0;
}

如果它有幫助,這是完整的編譯行+編譯錯誤:

$ g++ -o main main.cpp
main.cpp: In function ‘int main(int, char**)’:
main.cpp:19:14: error: no matching function for call to ‘Derived::Derived(Time*)’
  Derived d(&t);
              ^

您可以通過將Base類構造函數引入Derived類的范圍來實現:

class Derived : public Base
{
public:
    using Base::Base;  // Pull in the Base constructors

    // Rest of class...
};

在一個不相關的說明中,我真的建議不要使用指針。 在這種情況下根本不需要它。 相反,通過價值。 這將使您的Base構造函數更簡單:

Base(Time in_time)
    : time(in_time)
{}

您可以將所有基類構造函數放入子類的范圍中,如下所示

class Derived : public Base {
  public:
    using Base::Base;

  /* ... */
};

它允許完全使用場景

Time t = {30,7};
Derived d(&t);

請注意, using Base::Base始終會傳送Base聲明的所有構造函數。 沒有辦法省略一個或多個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM