2012-12-04 41 views
0

下面的代碼初始化對象的時候給我「不匹配呼叫」後聲明

test2.cc:248:14: error: no match for call to '(Integrator) (Input, double)' 
test2.cc:249:11: error: no match for call to '(Integrator) (Integrator&, double)' 
上編譯

class Integrator : public Block { 
    private: 
      ... 
     Input input;  
     double init_value;    
    public: 
     Integrator(); 
     Integrator(Input i, double initval = 0) : input(i), init_value(initval) {} 
     Integrator(Integrator &i, double initval = 0) : input(i), init_value(initval) {} 
... 
}; 

// + is overloaded 
Input operator + (Input a, Input b) { return new Add(a,b); } 

int main() { 
    Constant a(4.0); // Input 
    Integrator x,y; 
    ... 
    x(y + a, 0.0); // + is overloaded for Inputs 
    y(x, -2.0); 
    ... 
} 

因爲這是我的家庭作業,所以我只發佈了一小段代碼。如果這些還不夠,我可以添加更多。我看到類似的代碼工作,所以我試圖使用它(一些編輯),但它不適合我...

+0

謝謝大家。我是C++的新手,我有點困惑,所以有時我會忘記基本原理。 – milano

回答

2

你不能初始化對象聲明後。 x()嘗試將x作爲函數。

2

你試圖做的只會在初始化時起作用。 或者您需要創建一個採用這種參數的成員函數。

Integrator x; 
x(1.2) // Calling the constructor doesn't make sense here 

您只能在初始化時直接調用構造函數(如前所述)。

Integrator x(1.2) ; 

成員函數聽起來像是要走的路。

2

在定義完成後,您無法使用構造函數「初始化」對象。你可以做的是覆蓋operator()函數你想要的語法:

class Integrator : public Block { 
    ... 

public: 
    void operator()(Input i, double initval = 0) 
     { 
      input = i; 
      init_value = initval; 
     } 

    ... 
}; 
+2

雖然這在技術上是可行的,但它會非常直觀地使用'operator()',導致維護頭痛。我強烈建議使用一個命名的成員函數。 – Angew

+0

@Joachim Pileborg我嘗試了你的例子(我稍後將改爲成員函數),並且錯誤更改爲對'Integrator :: Integrator()'的未定義引用,其中http://pastebin.com/JvFZLQ2n – milano