【问题标题】:Error of conversion when I create new Object创建新对象时的转换错误
【发布时间】:2013-11-02 19:28:45
【问题描述】:

我在新对象的实例中遇到了各种错误。这是我第一次用 C++ 编程,所以我什么都不知道,但我真的不知道我想念什么。以下是我的代码和相关错误的一些示例。

    Edge newEdge;
    newEdge = new Edge(vertex2, neighbors(vertex1));  // create a new edge without weight

出现的错误是:

invalid conversion from `Edge*' to `int' 
initializing argument 1 of `Edge::Edge(int, Edge*, unsigned int)' 

而构造函数是

public: Edge(int nextVertex = 0, Edge* ptr = NULL, unsigned int weight = 1):nextVertex(nextVertex),
                                                                           next(ptr),
                                                                           weight(weight){};

其他类也类似:

PriorityQueue queue = new PriorityQueue();

错误:

conversion from `PriorityQueue*' to non-scalar type `PriorityQueue' requested 

代码:

VertexPriority aux;

错误:

no matching function for call to `VertexPriority::VertexPriority()' 

最后

ShortestPath shortp = new ShortestPath(graph);

错误:

conversion from `ShortestPath*' to non-scalar type `ShortestPath' requested 

还有一个错误,我认为我限制了之前的错误,因为它是一个实例并且错误相似,这里是代码:

queue.insert(new VertexPriority(vertex1, 0));

错误是:

no matching function for call to `PriorityQueue::insert(VertexPriority*)' 
candidates are: void PriorityQueue::insert(VertexPriority) 

对象的构造函数是

VertexPriority(int vertex, unsigned int priority):vertex(vertex),
                                                        priority(priority){};

insert 方法接受一个顶点作为参数:void insert(VertexPriority vertex);

我在代码中遗漏了什么?

【问题讨论】:

  • 你错过了这不是 Java 或 C#。

标签: c++ pointers compiler-errors instance


【解决方案1】:

C++ 不是 Java,在创建普通的非指针对象时不要使用 new

原来如此

newEdge = Edge(vertex2, neighbors(vertex1));

这会导致调用复制赋值运算符,因此如果对象中有任何复杂数据,最好有一个。参见例如the rule of three.

【讨论】:

  • 好的,谢谢!实际上我来自 java,这是我的第一个 c++ 程序
  • 一直存在的问题是第三个:VertexPriority aux;如何解决?
  • @giacomotb 同理,不要使用new
  • 在这种情况下,我没有使用 new,我正在使用 VertexPriority aux; [...] 辅助 = queue.top();
  • @giacomotb 好的,我正在将你所有不同的东西混合在一起。如果您为VertexPriority 声明构造函数,无论如何,编译器都不会生成默认构造函数。所以你必须创建自己的默认构造函数,编译器说没有。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-02
  • 2021-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多