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

Mat*_*hew 9 c++ struct temporary

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

Emi*_*ier 8

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

struct Point {int x; int y;};

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

plot(makePoint(12, 34));
Run Code Online (Sandbox Code Playgroud)

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

// Not allowed when constructor is defined
const Point points[] = {{12,34}, {23,45}, {34,56}};
Run Code Online (Sandbox Code Playgroud)

VS

const Point points[] = {Point(12,34), Point(23,45), Point(34,56)};
Run Code Online (Sandbox Code Playgroud)

  • 请注意,在 C++11 中,即使定义了 `Point` 构造函数,use 也可以使用大括号初始化。在这种情况下,大括号内的参数将传递给构造函数。此功能称为[统一初始化](https://en.wikipedia.org/wiki/C%2B%2B11#Uniform_initialization)。 (2认同)

Man*_*uel 5

这在C++ 11标准中是可行的.基本上,你可以这样做:

struct_func(test_struct{5, 7});
Run Code Online (Sandbox Code Playgroud)

从版本4.4开始,这已在GCC中提供.

  • 事实上,您甚至不需要显式声明类型,除非大括号初始化列表可以创建的类型存在歧义:`#include <iostream> struct S { int i; 双 d;}; void f(S s) { std::cout << si << ' ' << sd << std::endl; } int main(int, char **) { f( {7, 42} ); }` 如果没有统一的初始化或 C++11 中所做的所有其他大规模升级(我完全认为这是理所当然的),我认为我永远不会成功。 (2认同)

joe*_*son 0

我不是 C++ 专家,但是您不能将创建语句放在函数调用的参数列表中吗?