簡體   English   中英

在C ++中繼承的單例

[英]Inherited singleton in C++

您能否檢查一下這段代碼:

#include <vector>
class A
{
public:
    A(int a, int b);
};

class C :public A
{
public:
    C(int a, int b):A(a,b){}
    static C instances;
};

C C::instances;

int main()
{
    return 1;
}

編譯給我的錯誤是:

$ c++ inheritance.cpp 
inheritance.cpp:16:6: error: no matching function for call to ‘C::C()’
inheritance.cpp:16:6: note: candidates are:
inheritance.cpp:12:2: note: C::C(int, int)
inheritance.cpp:12:2: note:   candidate expects 2 arguments, 0 provided
inheritance.cpp:8:7: note: C::C(const C&)
inheritance.cpp:8:7: note:   candidate expects 1 argument, 0 provided

我需要C繼承自A,並且我需要A在其構造函數中具有參數。 最后,我需要在沒有參數的情況下聲明和定義實例的靜態變量。 那么有解決方案嗎? 我重視您的評論。

需要注意的另一點:如果靜態變量是容器,例如:

靜態std :: vector實例;

該代碼將編譯就好了。 為什么?

編輯:

感謝您提供所有答案,但是,如果我修改CC::instances; CC::instances(0,0); 我將收到另一個錯誤:$ c ++ Inheritance.cpp /tmp/cctw6l67.o:在函數C::C(int, int)': inheritance.cpp:(.text._ZN1CC2Eii[_ZN1CC5Eii]+0x1b): undefined reference to A :: A(int,int)'collect2:ld返回1退出狀態

知道為什么嗎? 以及如何解決?

謝謝

如果定義了構造函數,則編譯器將不再為您生成默認的構造函數,而是嘗試使用CC::instances;進行調用CC::instances; 您可以通過調用可用的構造函數來繞過此操作:

C C::instances(0,0);

或為C提供默認的構造函數。

static std::vector<C> instances;

它會編譯,因為沒有創建任何元素,並且std::vector具有默認構造函數,該構造函數初始化了一個空向量。

C::instances.push_back(C());

不會編譯。

使用CC::instances; 您正在構造一個對象,因此調用其構造函數。

由於您為構造函數提供了兩個參數C(int a, int b) ,因此不會自動為您自動生成默認的構造函數(不需要)。 因此,您必須使用2個參數CC::instances(0, 0)創建CC::instances(0, 0)或者為C提供額外的默認構造函數:

C() : A(0, 0)
{
}

關於第一個問題:自上一行以來,您正在收到此錯誤

C C::instances;

嘗試調用不帶參數的C構造函數(即C::C() )。 您可以通過引入C::C()構造函數A::A(int, int)使用兩個默認值調用A::A(int, int)來解決此問題,也可以為現有構造函數指定默認值,例如

C::C(int a = 0, int b = 0) : A(a, b) {}

關於第二個問題: std::vector具有默認構造函數。

CC::instances;

這將嘗試調用默認構造函數,並且由於您提供了構造函數,因此編譯器將不提供該構造函數。

將默認構造函數添加到class A class Cclass C

class A
{
public:
   A(int a, int b);
   A() {}  // implement default constructor
 };

//class C
 class C :public A
 {
 public :

    C(int a, int b):A(a,b){}
     C() {} // default constructor
     static C instances;
  };

static std::vector instances;

這將起作用,因為std::vector具有默認的構造函數。

暫無
暫無

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

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