1

私のコードもここにあります。

このコードは機能します(ただし、コードの重複が多くあります)。

Employee::Employee(const Employee& x)
{
        name=new char [strlen(x.name)+1];
        strcpy(name, x. name);
        strcpy(EGN, x.EGN);
        salary=x.salary;
}

void Employee::operator=(const Employee& x)
{
        delete[] name;
        name=new char [strlen(x.name)+1];
        strcpy(name, x. name);
        strcpy(EGN, x.EGN);
        salary=x.salary;
}

Employee::Employee(char* n, char* e, double s)
{
        name = new char [strlen(n)+1];
        strcpy(name, n);
        strcpy(EGN, e);
        salary=s;
}

以下は、同じことを3回書くことを避けるための私の試みです...しかし、それは機能しません。そのコードを短くすることはできませんか?

Employee::Employee(char* n, char* e, double s)
{
        name = new char [strlen(n)+1];
        strcpy(name, n);
        strcpy(EGN, e);
        salary=s;
}

Employee::Employee(const Employee& x)
{
        Employee(x.name, x.EGN, x.salary);
}

void Employee::operator=(const Employee& x)
{
        delete[] name;
        Employee(x);
}
4

3 に答える 3

6

あなたが試みていることは、その言語では許可されていません。ただし、C ++ 11ではコンストラクターを委任できるため、次のように実行できます。

Employee::Employee(const Employee& x) : Employee(x.name, x.EGN, x.salary){}

一方のコンストラクターがもう一方の初期化リストで呼び出されることに注意してください。

C ++ 11以前は、すべてのコンストラクターから初期化関数のkinfを呼び出すオプションがありました。ただし、関数呼び出しは初期化ではなくメンバー変数への代入を実行するため、これは意味的に異なります。

于 2012-08-30T20:55:32.963 に答える
4

コンストラクターをメンバー関数として呼び出すことはできません。メンバー関数を作成し、コンストラクターや他のすべての場所から呼び出すことができます。

void Employee::Init(const char* n, const char* e, double s)
{
        name = new char [strlen(n)+1];
        strcpy(name, n);
        strcpy(EGN, e);
        salary=s;
}

void Employee::Init(const Employee &x)
{
        Init(x.name, x.EGN, x.salary);
}

Employee::Employee(char* n, char* e, double s)
{
    Init(n,e,s);
}


Employee::Employee(const Employee& x)
{
     Init(x);
}

void Employee::operator=(const Employee& x)
{
        delete[] name;
        Init(x);
}
于 2012-08-30T20:53:51.130 に答える
1

C++11でこれを試してください

Employee::Employee(char* n, char* e, double s)
{
        name = new char [strlen(n)+1];
        strcpy(name, n);
        strcpy(EGN, e);
        salary=s;
}

// Constructor chaining (delegation) like this.
Employee::Employee(const Employee& x)
    : Employee(x.name, x.EGN, x.salary)
{}


// Use copy and swap for the assignment operator:

// Common convention to return a reference to yourself to allow chaingin.
Employee& Employee::operator=(Employee x)   // Pass by value to get the copy.
{ 
    x.swap(*this);                          // Then swap members
    return *this;
}                                           // Destructor will then cleanup.
于 2012-08-30T21:07:56.070 に答える