在第43行的c代码中无效使用'counter :: counter'

时间:2013-11-28 17:41:45

标签: c++

我在以下代码中遇到错误无效使用'counter :: counter'

这是我的代码:

#include<iostream>
using namespace std;

class counter   
{
protected:
    int value;
public:
    counter ()
    {
        value=0;
    }
    counter (int val)
    {
        value=val;
    }
    int GetCounter()
    {
        return value;
    }
    counter up()
    {
        value=value+1;
    }
};
class NewCounter : public counter   
{
public:
    NewCounter():counter()
    {}
    NewCounter(int val):counter(int val)
    {}
    void Down()
    {
        value=value-1;
    }
};

int main(void)
{
    NewCounter con1;
    NewCounter con2;
    con2.counter(1);
    cout<<"Counetr Initially"<<con1.GetCounter()<<endl;
    cout<<"Counter initially"<<con2.GetCounter()<<endl;
    con1.up();
    con2.up();
    cout<<"Counter 1 on incrrr---"<<con1.GetCounter()<<endl;
    cout<<"Counter  2 on incrrr---"<<con2.GetCounter()<<endl;
    con1.Down();
    con2.Down();
    cout<<"count 1 on down"<<con1.GetCounter()<<endl;
    cout<<"count 2 on down"<<con2.GetCounter()<<endl;
    return 0;
}

3 个答案:

答案 0 :(得分:1)

在我看来,您正在尝试实例化NewCounter对象并将其数据成员设置为:

NewCounter con2;
con2.counter(1);

第二行是非法的,counter是一个无法像成员函数一样调用的构造函数。但你这样做了:

NewCounter con2(1);

如果您修复了NewCounter构造函数,那么这将有效:

NewCounter(int val):counter(val) {}

答案 1 :(得分:1)

在线:

con2.counter(1);

您正在调用子对象counter的构造函数。那是愚蠢和非法的。相反,您可以调用NewCounter(int)构造函数,int将传递给counter构造函数:

NewCounter con2(1);

答案 2 :(得分:1)

NewCounter con2;
con2.counter(1);

无; counter不是您可以调用的函数!

您可以一次性传递构造函数参数:

NewCounter con2(1);