2012-12-04 43 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