【问题标题】:Cannot create object when creating user-defined copy constructor创建用户定义的复制构造函数时无法创建对象
【发布时间】:2020-02-28 09:55:39
【问题描述】:

此代码在尝试添加复制构造函数之前有效。

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

上面的代码不起作用,它只有在我使用这种语法创建myLaptop 和oldLaptop 时才起作用:

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

【问题讨论】:

    标签: c++ class reference constants copy-constructor


    【解决方案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;
        }
    

    或者添加移动构造函数。

    考虑到您需要包含标头 &lt;string&gt; 而不是标头 &lt;string.h&gt;。

    #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;        
            }
    };
    //...
    

    【讨论】:

    • 这里的const 是什么意思?
    • @MayarKarout 表示常量引用。您不能将非常量引用绑定到临时对象。
    猜你喜欢
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    • 2019-07-25
    • 2023-03-21
    • 1970-01-01
    • 2011-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多