10

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


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

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

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

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

4

5 回答 5

10

在结构中提供构造函数的另一种方法是提供 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}};

对比

const Point points[] = {Point(12,34), Point(23,45), Point(34,56)};
于 2010-02-06T07:28:33.887 回答
7

这在C++11 标准中是可能的。基本上,您可以这样做:

struct_func(test_struct{5, 7});

从 4.4 版开始,这已在 GCC 中可用。

于 2010-02-06T07:15:26.137 回答
2

你可以像在课堂上那样做。只需给您的结构一个构造函数,您就可以像结构一样内联创建它。您对使用构造函数的反对是没有根据的。类和结构之间的主要区别在于与其关联的默认可见性。对于类,它是私有的;对于结构,公共。没有“样板”,您不必遵守任何您不想遵守的“约定”。

struct test_struct
{
    int a;
    short b;

    test_struct(int a_, int b_): a(a_), b(b_) { }
};

struct_func(test_struct(5, 7));
于 2010-02-06T07:13:26.177 回答
0

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

于 2010-02-06T07:07:58.777 回答
0

结构也可以有构造函数,所以你可以对它们做与类示例一样的事情。

于 2010-02-06T07:13:38.853 回答