Let's say I have c_student
class with several members and no constructors:
#include <iostream>
#include <string>
#include <initializer_list>
#include <typeinfo>
class c_student{
// private:
public:
std::string name = "John";
int mark = 5;
std::string second_name="Doe";
void print(){
std::cout << name <<" " << second_name << " : "<< mark<<"\n";
}
};
int main(){
c_student stud_c = {"Luke ",420};
stud_c.print();
c_student stud_d = {"Mark "};
stud_d.print();
}
This code works fine, but let's say I want to define custom constructors inside the class:
c_student (std::string n):name(n){};
c_student() = default;
If I add them to class, the compiler complains that:
47_object_initialization.cpp:32:34: error: could not convert ‘{"Luke ", 420}’ from ‘<brace-enclosed initializer list>’ to ‘c_student’
32 | c_student stud_c = {"Luke ",420};
| ^
| |
| <brace-enclosed initializer list>
I want to keep using default constructor for {} and so need to write something like:
c_student( std::initializer_list <???>) = default; << Pseudo-code only!
But can't get how exactly. Could anyone points my attention on the right page of CPP reference?
Aucun commentaire:
Enregistrer un commentaire