小编Mat*_*hew的帖子

在C++中通过值传递临时结构的简单方法?

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

c++ struct temporary

9
推荐指数
3
解决办法
9639
查看次数

标签 统计

c++ ×1

struct ×1

temporary ×1