1

您好,只是想知道在 C++03 中是否可以执行以下操作。我已经尝试过了,但对我不起作用。

struct SomeClass{
int a,b,c,d;
};

SomeClass * temp  = new SomeClass();
*temp = { 1,2,3,4};

我做到了,但编译器给了我一个警告,只有 C++11 才支持扩展初始化器。
在使用 new 创建对象时,是否有其他方法可以使用双括号初始化?不允许构造函数

4

2 回答 2

4

我不认为您可以直接在 C++03 中执行此操作,但与蛮力相比,您可以(也许)简化工作,您可能会将其视为“类外构造函数”:

struct someclass{
    int a, b, c, d;
};

someclass make(int a, int b, int c, int d) { 
    someclass ret = {a, b, c, d};
    return ret;
}

int main(){
    someclass *s = new someclass();

    *s = make(1, 2, 3, 4);
}

很容易打赌,任何相当新的(甚至可能是最古老的)C++ 编译器都会内联函数调用,因此函数调用不会带来任何开销。如果您愿意,您还可以将函数转换为模板,并为不同数量的参数重载它,因此您可以执行以下操作:

someclass *s = new someclass();

*s = make<someclass>(1, 2, 3, 4);

otherclass *o = new otherclass();

*o = make<otherclass>(1, 2);

然而,归根结底,这里最大的问题是你一开始就走错了路。有可能(至少)在接下来的一两年内,您应该完全忘记 C++ 有new表达式。感觉自己需要它(尤其是在这种情况下)是一个相当好的迹象,表明您还没有很好地适应 C++,并且仍在尝试编写 Java。

于 2013-02-05T07:45:27.943 回答
1

技术上当前C++C++11.

无论如何,没有C++11. 您只能在创建结构或数组时进行大括号初始化。

IE

SomeClass temp = { 1,2,3,4 };

编辑:我需要查看它在 C++ 中的支持,但这在 C99 中似乎是可能的,通过使用称为复合文字的东西

SomeClass temp;

temp = ((SomeClass){1,2,3,4});

Edit2 - 没有雪茄 -source.cpp:9:31: warning: ISO C++ forbids compound-literals [-pedantic]

好像其他人也有同样的问题

于 2013-02-05T07:09:04.477 回答