C ++ Using curly braces when assigning a class variable
When I declare an array in C ++, I can use curly braces like this:
int var[3] = {1, 2, 3};
Can curly braces be declared in a class, for example, as operator overloading? I mean for example:
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;
}
The code above is just my imaginary one, but I want to use curly braces as this code.
source to share
You may need a constructor with 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();
}
Another approach is to use the variable constructor constructor (I find it less readable, but it has the advantage that your code is 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...);
}
};
Note:
In C ++, no operator{}
.
source to share
If you can use modern C ++ (like C ++ 11), you can use std :: initializer_list . Most modern compilers support it, just add -std=c++11
the compile flag
source to share