簡體   English   中英

C++ 錯誤:試圖理解類和構造函數

[英]C++ error: trying to understand Classes and Constructors

我試圖了解我收到的錯誤:

錯誤:被隱式刪除,因為默認定義格式錯誤

調查我收到錯誤的原因,我認為這與沒有class Dealer的默認構造函數有關。 我不太明白為什么這個程序會出現這種情況。 我相信這與我創建的Motorcycle m_motorcycle object 有關。

#include <iostream>
using namespace std;

class Motorcycle{

public:
    string m_make;
    string m_model;
    int m_year;
    Motorcycle(string, string, int);
};

class Dealer{
private:
    Motorcycle m_motorcycles[3];
public:
    void addMotorcycle(Motorcycle);
    Motorcycle getMotorcycle(int);
};

int main(){
    Motorcycle bike1("Ductai", "Scrambler", 2020);
    Dealer dealer1;

    dealer1.addMotorcycle(bike1);
    return 0;
}

Motorcycle::Motorcycle(string make, string model, int year){
  this->m_make = make;
  this->m_model = model;
  this->m_year = year;
}
void Dealer::addMotorcycle(Motorcycle bike){
    this->m_motorcycles[0] = bike;
}

Dealer的初始化需要初始化Motorcycle m_motorcycles[3]; ,當它嘗試創建一個Motorcycle數組時,它會查找其默認構造函數,但只提供了一個參數化構造函數。

class Motorcycle{
public:
    string m_make;
    string m_model;
    int m_year;
    Motorcycle(string, string, int);
    Motorcycle(){ 
        //.....
    }; 
};

將默認構造函數添加到Motorcycle將是修復它的一種方法。

錯誤是說class Dealer的隱式默認構造函數被刪除,因為它包含Motorcycle m_motorcycles[3]; ,並且Motorcycle沒有默認構造函數。

解決此問題的一種方法是包含std::vector<Motorcycle> m_motorcycles; class Dealer而不是數組中,並更改Dealer::addMotorcycle()

void Dealer::addMotorcycle(Motorcycle bike){
    this->m_motorcycles.push_back( bike );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM