创建用户定义的复制构造函数时无法创建对象

Cannot create object when creating user-defined copy constructor

提问人:Mayar Karout 提问时间:11/2/2019 最后编辑:Vlad from MoscowMayar Karout 更新时间:11/2/2019 访问量:25

问:

此代码在尝试添加复制构造函数之前起作用。

#include <iostream>
#include <string.h>

using namespace std;

class Laptop
{
    public:
        string brand;
        string model;
        int ram;
        int storage;

        Laptop(string brand, string model, int ram, int storage)
        {
            this->brand = brand;
            this->model = model;
            this->ram = ram;
            this->storage = storage;
        }
        Laptop(Laptop &x)
        {
            this->brand = x.brand;
            this->model = x.model;
            this->ram = x.ram;
            this->storage = x.storage;
        }
        void displayData()
        {
            cout << brand << " " << model << ": RAM = " << ram << "GB, Storage = " << storage << "GB" << endl;        
        }
};

int main()
{
    Laptop myLaptop = Laptop("Asus", "Zenbook", 16, 2048);
    Laptop copyOriginal = Laptop(myLaptop);

    copyOriginal.displayData();

    return 0;
}

上面的代码不起作用,它只有在我创建和使用以下语法时才有效:myLaptopoldLaptop

Laptop myLaptop("Asus", "Zenbook", 16, 2048);
Laptop copyOriginal(myLaptop);
C++ 引用 常量 copy-constructor

评论


答:

0赞 Vlad from Moscow 11/2/2019 #1

您不能将非常量引用绑定到临时对象,例如,在此声明中,右侧是临时对象

Laptop myLaptop = Laptop("Asus", "Zenbook", 16, 2048);

声明副本如下

    Laptop( const Laptop &x)
    {
        this->brand = x.brand;
        this->model = x.model;
        this->ram = x.ram;
        this->storage = x.storage;
    }

或者添加移动构造函数。

考虑到您需要包含标题而不是标题。<string><string.h>

#include <string>

您的班级可以按以下方式显示

#include <iostream>
#include <string>
#include <utility>

using namespace std;

class Laptop
{
    public:
        string brand;
        string model;
        int ram;
        int storage;

        Laptop( const string &brand, const string &model, int ram, int storage)
            : brand( brand ), model( model ), ram( ram ), storage( storage )
        {
        }


        Laptop( const Laptop &x)
            : brand( x.brand ), model( x.model ), ram( x.ram ), storage( x.storage )
        {
        }

        Laptop( Laptop &&x)
            : brand( std::move( x.brand ) ), model( std::move( x.model ) ), ram( x.ram ), storage( x.storage )
        {
        }

        void displayData() const
        {
            cout << brand << " " << model << ": RAM = " << ram << "GB, Storage = " << storage << "GB" << endl;        
        }
};
//...

评论

0赞 Mayar Karout 11/2/2019
这是什么意思?const
0赞 Vlad from Moscow 11/2/2019
@MayarKarout 表示常量引用。不能将非常量引用绑定到临时对象。