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

In C++98 'dvd1' must be initialized by constructor, not by '{...}'

如何初始化 dvd1?

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

Question1.cpp: In function 'int main()':

Question1.cpp:39:76: error: in C++98 'dvd1' must be initialized by constructor, not by '{...}'

dvd dvd1 = {"Zombie","BBC","James","English","Alw",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();
}

这称为 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);

dvd是非aggregate type, which can't be initialized with braced intializer until C++11, which supports list initialization。 (更准确地说,您要做的是复制列表初始化。)

对于 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 有一个用户定义的构造函数,然后将其取消。