Mat*_*hew 9 c++ struct temporary
假设我想将临时对象传递给函数.有没有办法在1行代码中对比2,用结构?
有了课,我可以做:
class_func(TestClass(5, 7));
Run Code Online (Sandbox Code Playgroud)
给定:
class TestClass
{
private:
int a;
short b;
public:
TestClass(int a_a, short a_b) : a(a_a), b(a_b)
{
}
int A() const
{
return a;
}
short B() const
{
return b;
}
};
void class_func(const TestClass & a_class)
{
printf("%d %d\n", a_class.A(), a_class.B());
}
Run Code Online (Sandbox Code Playgroud)
现在,我如何使用结构?我最接近的是:
test_struct new_struct = { 5, 7 };
struct_func(new_struct);
Run Code Online (Sandbox Code Playgroud)
给定:
struct test_struct
{
int a;
short b;
};
void struct_func(const test_struct & a_struct)
{
printf("%d %d\n", a_struct.a, a_struct.b);
}
Run Code Online (Sandbox Code Playgroud)
对象更简单,但我想知道是否有一种方法可以根据函数调用进行结构成员初始化,而不给结构提供构造函数.(我不想要一个构造函数.我使用结构的全部原因是避免在这个孤立的情况下使用样板get/set类约定.)
在结构中提供构造函数的另一种方法是提供make_xxx自由函数:
struct Point {int x; int y;};
Point makePoint(int x, int y) {Point p = {x, y}; return p;}
plot(makePoint(12, 34));
Run Code Online (Sandbox Code Playgroud)
您可能希望避免在结构中构造函数的一个原因是允许在结构数组中进行大括号初始化:
// Not allowed when constructor is defined
const Point points[] = {{12,34}, {23,45}, {34,56}};
Run Code Online (Sandbox Code Playgroud)
VS
const Point points[] = {Point(12,34), Point(23,45), Point(34,56)};
Run Code Online (Sandbox Code Playgroud)
这在C++ 11标准中是可行的.基本上,你可以这样做:
struct_func(test_struct{5, 7});
Run Code Online (Sandbox Code Playgroud)
从版本4.4开始,这已在GCC中提供.