C++ 错误 C2440:“正在初始化”:无法从“初始化列表”转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33327497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 14:15:15  来源:igfitidea点击:

error C2440: 'initializing' : cannot convert from 'initializer-list'

c++visual-studioconstructorinitializer-list

提问by Fatima Rashid

#include<iostream>
using namespace std;
struct TDate
{
    int day, month, year;
    void Readfromkb()
    {
        cout << "\n ENTER DAY MONTH YEAR\n";
        cin >> day >> month >> year;
    }
    void print()
    {
        cout << day << month << year;
    }
    private:
        int ID;
        bool valid;

};
int main()
{
    TDate t1, t2,t3={ 1, 2, 3 };
    t1.Readfromkb();
    t1.print();
    cin.ignore();
    cin.get();
    return 0;

}

why i'm getting Error 1 error C2440: 'initializing' : cannot convert from 'initializer-list' to 'TDate' and 2 IntelliSense: too many initializer values. When I remove bool valid and int ID the programs works.Why is it so?

为什么我收到错误 1 ​​错误 C2440:“正在初始化”:无法从“初始化列表”转换为“TDate”和 2 IntelliSense:初始化值太多。当我删除 bool valid 和 int ID 时,程序会工作。为什么会这样?

回答by Oblomov

You are getting the error because you are trying to initialize a TDatefrom an aggregate initialization list. This cannot be done when the type has private members (such as, in your case, IDand valid).

您收到错误是因为您试图TDate从聚合初始化列表中初始化 a 。当类型具有私有成员(例如,在您的情况下,IDvalid)时,这无法完成。

You can work around this by providing a constructor for your struct from three ints and using TDate t1, t2, t3(1, 2, 3).

您可以通过从三个ints为您的结构提供构造函数并使用TDate t1, t2, t3(1, 2, 3).

回答by vishal

To do t3={ 1, 2, 3 };you have to make constructor of TDate with takes three arguments, like this:

为此, t3={ 1, 2, 3 };您必须使用三个参数来制作 TDate 的构造函数,如下所示:

TDate(int i, int i1, int i2);

and implement it using:

并使用以下方法实现它:

TDate::TDate(int i, int i1, int i2) {

}

if you dont want to create constructor, then create object like this:

如果你不想创建构造函数,那么创建这样的对象:

TDate t1 = TDate();