在C ++ 98' dvd1'必须由构造函数初始化,而不是由' {...}'

时间:2017-07-10 08:40:41

标签: c++ c++98

如何初始化dvd1?

C:\Users\SuperUser\Google Drive>g++ -o a Question1.cpp

  

Question1.cpp:在函数' int main()':

     

Question1.cpp:39:76:错误:在C ++ 98' dvd1'必须由构造函数初始化,而不是由' {...}'

初始化      

dvd dvd1 = {" Zombie"," BBC"," James","英语"," Alw&#34 ;,2012,20170601,20170630};

#include <iostream>
#include <string>

using namespace std;

class dvd
{
    string movieName,movieProdComp,movieLeadActor,movieLanguage,renterName;
    int releaseYear,rentDate,returnDate;
    public:

        dvd(string mn,string mpc,string mla,string ml, string rn,int ry,int rd,int retd);
        void print();
};

dvd::dvd(string mn,string mpc,string mla,string ml, string rn, int ry,int rd,int retd){
    movieName=mn;
    movieProdComp=mpc;
    movieLeadActor=mla;
    movieLanguage=ml;
    renterName=rn;
    releaseYear=ry;
    rentDate=rd;
    returnDate=retd;
}

void dvd::print(){
    cout<<"Movie:"<<movieName<<endl;
    cout<<"Production:"<<movieProdComp<<endl;
    cout<<"Starring:"<<movieLeadActor<<endl;
    cout<<"Language:"<<movieLanguage<<endl;
    cout<<"Rented By:"<<renterName<<endl;
    cout<<"Released:"<<releaseYear<<endl;
    cout<<"Rent Date:"<<rentDate<<endl;
    cout<<"Return Date:"<<returnDate<<endl;
}

int main(){
    dvd();
    dvd dvd1 = {"Zombie","BBC","James","English","Alw",2012,20170601,20170630};
    dvd1.print();
}

2 个答案:

答案 0 :(得分:5)

dvd是非aggregate type,无法使用支撑的初始化程序进行初始化,直到支持list initialization的C ++ 11。 (更准确地说,您尝试做的是复制列表初始化。)

对于C ++ 98,您可以编写

dvd dvd1 ("Zombie","BBC","James","English","Alw",2012,20170601,20170630);
dvd dvd1 = dvd("Zombie","BBC","James","English","Alw",2012,20170601,20170630);

在C ++ 98中,只有当dvd dvd1 = {...};为聚合类型时才可以使用aggregate initialization;对于这种情况,dvd具有用户定义的构造函数,然后不是。

答案 1 :(得分:2)

这称为list initialization,对于非聚合类型,它仅在C ++ 11中受支持:

dvd dvd1 = {"Zombie","BBC","James","English","Alw",2012,20170601,20170630};

对于C ++ 98,你可能想稍微改一下,像往常一样调用构造函数:

dvd dvd1("Zombie","BBC","James","English","Alw",2012,20170601,20170630);