假设我想将临时对象传递给函数.有没有办法在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类约定.)