#include <iostream>
#include <vector>
int main() {
std::vector<int> v1(10);
std::vector<int> v2{10};
for (int x : v1)
std::cout << x << ", ";
std::cout << std::endl;
for (int x : v2)
std::cout << x << ", ";
}
makes
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
10,
How can C distinguish between () and {} when initialising a class?
And how can I create a constructor for both () and {} with different meanings?
CodePudding user response:
How can C distinguish between () and {} when initialising a class?
Because they are using different syntaxes, so the compiler can parse them differently and behave accordingly.
how can I create a constructor for both () and {} with different meanings?
Define 2 constructors, making one of them take a std::initializer_list
as a parameter. {}
will call that constructor. ()
will call the other one.