【问题标题】:Casting an Array Literal in C++ to a type (VC++)将 C++ 中的数组文字转换为类型 (VC++)
【发布时间】:2012-03-31 00:12:36
【问题描述】:

假设我有一个类型优势:

struct edge
{
    long long weight;
    int dest;
    inline bool operator<(const edge& other) const
    {
        return weight > other.weight;
    }
};

在 G++ 4.1.2 (CentOS) 中我可以安全地做到:

edge e = (edge){0, 1};

但在 MSVC++ 2010 上,相同的代码会导致:

test.cpp(57) : error C2059: syntax error : '{'
test.cpp(57) : error C2143: syntax error : missing ';' before '{'
test.cpp(57) : error C2143: syntax error : missing ';' before '}'

有没有办法在 MSVC++ 编译器中做到这一点?

【问题讨论】:

  • 哦,好的,我刚试过,它有效。我一直在使用 G++,并且一直在看到其他人使用它,所以我认为这是唯一的选择。谢谢!
  • 是的,演员阵容对我来说也很奇怪。语法(没有演员表)一直追溯到 K&R C。
  • @Marlon 很抱歉打扰,但如果我有一个 std::priority_queue 的边,我不能推入一个数组文字..
  • 对于推送,为什么不创建一个将两个值作为参数的构造函数,然后您可以在推送中创建一个新实例,例如container.push_back(edge(weight, dest));.
  • 你一直在说“数组字面量”,但这里没有这样的东西——edge e = { 0, 1 }; 被称为聚合初始化并且不涉及数组。

标签: c++ visual-c++ gcc g++


【解决方案1】:

我建议有一个构造函数:

struct edge  {
   long long weight;
   int dest;
   edge(long long w, int d): weight(w), dest(d) {};
   inline bool operator<(const edge& other) const {
    return weight > other.weight;
   }
};

然后使用

edge e (0,1);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 1970-01-01
    • 1970-01-01
    • 2011-05-17
    相关资源
    最近更新 更多