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

2024-04-06

假设我想将一个临时对象传递给一个函数。有没有办法用 1 行代码和 2 行代码来使用结构来做到这一点?


通过一堂课,我可以做到:

class_func(TestClass(5, 7));

given:

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);

given:

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 类约定。)


在结构中提供构造函数的另一种方法是提供 make_xxx 自由函数:

struct Point {int x; int y;};

Point makePoint(int x, int y) {Point p = {x, y}; return p;}

plot(makePoint(12, 34));

您可能希望避免结构中的构造函数的原因之一是允许在结构数组中进行大括号初始化:

// Not allowed when constructor is defined
const Point points[] = {{12,34}, {23,45}, {34,56}};

vs

const Point points[] = {Point(12,34), Point(23,45), Point(34,56)};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 C++ 中按值传递临时结构的简单方法? 的相关文章

随机推荐