无法将{...}从<brace-enclosed initializer =“”list =“”>转换为struct

时间:2016-06-12 16:55:51

标签: c++ gcc struct initialization

我之前使用过TDM-GCC-5.10,现在切换回4.9 MINGW-GCC并尝试使用列表初始化时遇到奇怪的错误:

class Vector2
{
public:
    Vector2(float x, float y)
    {
        this->x = x;
        this->y = y;
    }
    float x = 0.f;
    float y = 0.f;
};

struct Test
{
    int x = 0;
    Vector2 v;
};

int main()
{    
    Test tst = {0,Vector2(0.0f,0.0f)}; //Error
    return 0;
}

错误:

main.cpp: In function 'int main()':
main.cpp:21:41: error: could not convert '{0, Vector2(0.0f, 0.0f)}' from '<brace-enclosed initializer list>' to 'Test'
         Test tst = {0,Vector2(0.0f,0.0f)}; //Error
                                         ^

我在两个编译器中都使用了C ++ 14。有什么问题?

3 个答案:

答案 0 :(得分:19)

问题在于:

struct Test
{
    int x = 0; // <==
    Vector2 v;
};

直到最近,默认成员初始值设定项阻止该类成为聚合,因此您无法对它们使用聚合初始化。 Gcc 4.9仍然在这里实现旧规则,而gcc 5使用新规则。

答案 1 :(得分:2)

您在课程定义后和contains()之后错过了;。然后你得到了很多错误,显然只考虑了最后一个错误。但是你的编译器很困惑,因为没有定义int x = 0(由于缺少Vector2)。

编译:

;

答案 2 :(得分:1)

// 10.3  lowest common ancestor

// Solution: A brute-force approach is to see if the nodes are in different
// immediate subtrees of the root, or if one of the nodesis the root

#include <bits/stdc++.h>
using namespace std;
template <typename T>
struct Node {
  T data;

  unique_ptr<Node<T>> left;
  unique_ptr<Node<T>> right;
};

struct Status {
  int num_target_nodes;
  //   Node<int>* ancestor;
  unique_ptr<Node<int>> ancestor;
};

Status lcaHelper(unique_ptr<Node<int>>& root, unique_ptr<Node<int>>& node0,
                 unique_ptr<Node<int>>& node1) {
  if (root == nullptr) {
    return {0, nullptr};
  }

  auto l = lcaHelper(root->left, node0, node1);

  if (l.num_target_nodes == 2) return l;

  auto r = lcaHelper(root->right, node0, node1);

  if (r.num_target_nodes == 2) return r;

  int num_target_nodes = l.num_target_nodes + r.num_target_nodes +
                         (root == node0) + (root == node1);

  return {num_target_nodes, num_target_nodes == 2 ? root : nullptr};

  //   return {num_target_nodes, num_target_nodes == 2 ? root.get() :
  //   nullptr};
}

// Node<int>* lca(unique_ptr<Node<int>>& root, unique_ptr<Node<int>>& node0,
//                unique_ptr<Node<int>>& node1) {
unique_ptr<Node<int>> lca(unique_ptr<Node<int>>& root,
                          unique_ptr<Node<int>>& node0,
                          unique_ptr<Node<int>>& node1) {
  return lcaHelper(root, node0, node1).ancestor;
}

int main() {}

我尝试了elements of programming interview一书中的类似示例。它显示了相同的问题,上面的答案不适用于这种情况。我在gcc版本8.3.0(Ubuntu 8.3.0-6ubuntu1)中使用g ++ -std = c ++ 11

相关问题