当我在C++中声明一个数组时,我可以像这样使用大括号:
int var[3] = {1, 2, 3};
Run Code Online (Sandbox Code Playgroud)
我可以在类中使用大括号声明,比如运算符重载吗?我的意思是,像这样:
class example
{
private:
int m_sum;
public:
void operator{}(int a, int b, int c)
{
m_sum = a+b+c;
}
int get_sum()
{
return m_sum;
}
}
int main()
{
example ex = {1, 2, 3};
std::cout << ex.get_sum() << endl; // prints 6
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码只是我的想象,但我想使用大括号作为此代码.
qua*_*dev 10
You might want a constructor taking an std::initializer_list :
#include <iostream>
#include <algorithm>
#include <initializer_list>
class example
{
private:
int m_sum;
public:
example(std::initializer_list<int> parameters)
{
m_sum = std::accumulate(std::begin(parameters), std::end(parameters), 0);
}
int get_sum() const
{
return m_sum;
}
};
int main() {
example e = { 1, 2, 3, 4 };
std::cout << e.get_sum();
}
Run Code Online (Sandbox Code Playgroud)
Another approach is to use a variadic template constructor (I find it less readable, but it has the advantage of making your code generic : you can pass arbitrary elements to the constructor) :
#include <iostream>
#include <algorithm>
#include <initializer_list>
class example
{
private:
int m_sum;
public:
template <class... Ts> example(Ts&&... vs) : m_sum(compute_sum(vs...)) { }
int get_sum() const
{
return m_sum;
}
private:
template<typename Ts1>
Ts1 compute_sum(const Ts1& val) { return val; } // termination
template<typename Ts1, typename... Ts>
Ts1 compute_sum(const Ts1& arg1, const Ts&... args)
{
return arg1 + compute_sum(args...);
}
};
Run Code Online (Sandbox Code Playgroud)
Note:
There is no operator{} in C++.
| 归档时间: |
|
| 查看次数: |
1583 次 |
| 最近记录: |