在 C++ 中按值传递临时结构的简单方法? [英] Simple way to pass temporary struct by value in C++?

查看:22
本文介绍了在 C++ 中按值传递临时结构的简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose I want to pass a temporary object into a function. Is there a way to do that in 1 line of code vs. 2, with a struct?

通过课堂,我可以做到:

With a class, I can do:

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

<小时>

现在,我如何用结构体做到这一点?我得到的最接近的是:


Now, how do I do that with a struct? The closest I've got is:

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

The object is more simple, but I wonder if there's a way to do the struct member initialization right in line with the function call, without giving the struct a constructor. (I don't want a constructor. The whole reason I'm using a struct is to avoid the boilerplate get/set class conventions in this isolated case.)

推荐答案

在结构中提供构造函数的另一种方法是提供一个 make_xxx 免费函数:

An alternative to providing a constructor in your struct, would be to provide a make_xxx free function:

struct Point {int x; int y;};

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

plot(makePoint(12, 34));

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

One reason why you might want to avoid constructors in structs is to allow brace-initialization in arrays of structs:

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

对比

const Point points[] = {Point(12,34), Point(23,45), Point(34,56)};

这篇关于在 C++ 中按值传递临时结构的简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆