【问题标题】:Error calling the constructor调用构造函数时出错
【发布时间】:2014-07-15 22:48:40
【问题描述】:

我对 OOP 有点陌生,我对派生类中的构造函数有一个小问题。

我有以下代码:

class Functionar{
    protected:
        char nume[20];
        int cnp;
    public:
        Functionar(char *n,int c){strcpy(nume,n); cnp=c;}
        virtual void Afisare();
};

void Functionar::Afisare()
{
    cout<<"Nume: "<<nume<<endl<<"CNP: "<<cnp<<endl;
}

class Permanent:public Functionar{
    protected:
        int salariu;
        int nrorelucrate;
    public:
        //Permanent(char *n,int c,int s,int nr): Functionar(char *n,int c),salariu(s),nrorelucrate(nr){}
        Permanent(char *n,int c,int s,int nr)
        {
            Functionar(char *n,int c);
            salariu=s;
            nrorelucrate=nr;
        }
        //void Afisare();

};
main()
{
    Functionar Claudiu("Claudiu",495);
    Claudiu.Afisare();
}

很抱歉变量和函数名称。他们可能看起来有点奇怪。这个想法是我想在派生类中使用 numecnp 的基本构造函数创建一个构造函数。

我有几个错误:

In constructor 'Permanent::Permanent(char*, int, int, int)':
[Error] no matching function for call to 'Functionar::Functionar()'
[Note] candidates are:
[Note] Functionar::Functionar(char*, int)
[Note] candidate expects 2 arguments, 0 provided
[Note] Functionar::Functionar(const Functionar&)
[Note] candidate expects 1 argument, 0 provided
[Error] expected primary-expression before '(' token
[Error] expected primary-expression before 'char'
[Error] expected primary-expression before 'int'
C:\Users\Stefan\Desktop\Probleme Culegere POO\problema12.cpp    In function 'int main()':
[Warning] deprecated conversion from string constant to 'char*' [-Wwrite-strings]

我不明白为什么 'Functionar::Functionar()' 不匹配。谢谢。

【问题讨论】:

    标签: c++ oop constructor derived-class


    【解决方案1】:

    你应该使用构造函数的初始化列表来调用基类的构造函数(特别是对于带参数的ctors),例如:

    Permanent(char *n, int c, int s, int nr) : Functionar(n, c), salariu(s), nrorelucrate(nr) {}
    

    【讨论】:

      【解决方案2】:

      使用

      Permanent(char *n,int c,int s,int nr) :
              Functionar(n,c) 
              //your other variables go here
      {
      }
      

      如果没有初始化列表,则需要默认构造函数,因为该类会尝试默认初始化其基类。

      即使您确实有 Functionar 的默认构造函数,您的版本也只会创建一个临时对象,该对象会在 ; 之后被销毁,并且不会像您期望的那样初始化基础。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-08
        相关资源
        最近更新 更多