假设我想将一个临时对象传递给一个函数。有没有办法在 1 行代码与 2 行代码中使用结构来做到这一点?
通过一堂课,我可以做到:
class_func(TestClass(5, 7));
给定:
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());
}
现在,我如何使用结构来做到这一点?我得到的最接近的是:
test_struct new_struct = { 5, 7 };
struct_func(new_struct);
给定:
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);
}
该对象更简单,但我想知道是否有一种方法可以根据函数调用进行结构成员初始化,而无需为结构提供构造函数。(我不想要构造函数。我使用结构的全部原因是在这种孤立的情况下避免样板的 get/set 类约定。)