如何让列表可以隐式转换为我的 class 对象?
How to let list can convert to my class object implicitly?
比如我有一个classPoint
并且有一个函数
void foo(Point pt);
称之为
foo({1, 2, 3});
你必须有接受三个整数的构造函数。考虑:
struct Point {
Point (int p1_, int p2_, int p3_) : p1 {p1_}, p2 {p2_}, p3 {p3_} {}
int p1;
int p2;
int p3;
};
void foo (Point pt) {
std::cout << pt.p1 << std::endl;
std::cout << pt.p2 << std::endl;
std::cout << pt.p3 << std::endl;
}
和用法:
foo ({1, 2, 3});
std::cout << std::endl;
foo ({4, 5, 6});
#include <initializer_list>
#include <cassert>
struct bar
{
void foo(const std::initializer_list<int>& bits)
{
assert(bits.size() == 3);
auto i = bits.begin();
x = *i++;
y = *i++;
z = *i++;
}
int x, y, z;
};
int main()
{
bar b;
b.foo({0, 1, 2});
}
比如我有一个classPoint
并且有一个函数
void foo(Point pt);
称之为
foo({1, 2, 3});
你必须有接受三个整数的构造函数。考虑:
struct Point {
Point (int p1_, int p2_, int p3_) : p1 {p1_}, p2 {p2_}, p3 {p3_} {}
int p1;
int p2;
int p3;
};
void foo (Point pt) {
std::cout << pt.p1 << std::endl;
std::cout << pt.p2 << std::endl;
std::cout << pt.p3 << std::endl;
}
和用法:
foo ({1, 2, 3});
std::cout << std::endl;
foo ({4, 5, 6});
#include <initializer_list>
#include <cassert>
struct bar
{
void foo(const std::initializer_list<int>& bits)
{
assert(bits.size() == 3);
auto i = bits.begin();
x = *i++;
y = *i++;
z = *i++;
}
int x, y, z;
};
int main()
{
bar b;
b.foo({0, 1, 2});
}