Skip to content

Commit a003eb6

Browse files
author
Wang Jiazi
committed
initializer_list VS constructor
1 parent 74b08a1 commit a003eb6

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

C++/C++11/InitializerList/test.cpp

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#include <string>
2+
#include <iostream>
3+
#include <initializer_list>
4+
5+
class People {
6+
public:
7+
People(int id, std::string name):mId(id), mName(name) { std::cout<<"Normal Constructor\n";}
8+
People(std::initializer_list<std::pair<int, std::string>> s) {std::cout<<"Initializer_list Constructor\n";}
9+
10+
People(int, int) {std::cout<<"Normal Constructor2\n";}
11+
People(std::initializer_list<int>) {std::cout<<"Initializer_list Constructor2\n";}
12+
private:
13+
int mId;
14+
std::string mName;
15+
};
16+
17+
/*
18+
"{}" is used to initialize object the constructor whose parameter type is initializer_list should be picked firstly; if failed, then normal constructor is chosen.
19+
"()" is used to initialize object the constructor whose parameter type is non-initialize_list should be picked.
20+
*/
21+
int main()
22+
{
23+
24+
People P1={123, "One"}; //Normal Constructor
25+
People P2={std::pair<int, std::string>(123, "One"), std::pair<int, std::string>(1234, "Two")}; //Initializer_list Constructor
26+
People P3={123, 123}; //Initializer_list Constructor2
27+
People P4={123, "a"}; //Normal Constructor
28+
People P5={123, 'a'}; //Initializer_list Constructor2
29+
People P6(123, 123); //Normal Constructor2
30+
/*
31+
error: no matching function for call to ‘People::People(std::pair<int, std::basic_string<char> >)’
32+
People P7(std::pair<int, std::string>(123, "One"));
33+
*/
34+
People P7({std::pair<int, std::string>(123, "One")}); //Initializer_list Constructor
35+
}

0 commit comments

Comments
 (0)