如何正确地从运算符构造函数中调用复制构造函数?

时间:2012-08-30 20:50:39

标签: c++ operator-keyword copy-constructor function-call

我的代码也可以找到here

这段代码可行(但代码重复很多):

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;
}

以下是我试图避免三次写同样的事情......但它不起作用。是不是可以缩短代码?

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);
}

3 个答案:

答案 0 :(得分:6)

语言不允许您尝试的内容。但是,C ++ 11允许delegating constructors,所以你可以这样做:

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

请注意,在另一个的初始化列表中调用一个构造函数。

在C ++ 11之前,一个选项就是从所有构造函数调用一些初始化函数。但是,这在语义上是不同的,因为函数调用执行成员变量的赋值,而不是初始化。

答案 1 :(得分: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);
}

答案 2 :(得分: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.