使用g++编译主模块时出现奇怪错误

strange error compiling main module using g++

本文关键字:错误 g++ 编译 模块 使用      更新时间:2023-10-16

我正试图使用"g++main.cpp-c"编译下面的代码,但它给了我一个奇怪的错误。。有什么想法吗?

main.cpp: In function ‘int main()’:
main.cpp:9:17: error: invalid conversion from ‘Graph*’ to ‘int’
main.cpp:9:17: error:   initializing argument 1 of ‘Graph::Graph(int)’
main.cpp:10:16: warning: deprecated conversion from string constant to ‘char*’

这是我试图编译的主要模块,下面是我在graph.hpp 中的图形类

#include <iostream>
#include "graph.hpp"
using namespace std;
int main()
{
  Graph g;
  g = new Graph();
  char* path = "graph.csv";
  g.createGraph(path);
  return 0;
}

这是我的图形类

    /*
 * graph.hpp
 *
 *  Created on: Jan 28, 2012
 *      Author: ajinkya
 */
#ifndef _GRAPH_HPP_
#define _GRAPH_HPP_
#include "street.hpp"
#include "isection.hpp"
#include <vector>
class Graph
{
 public:
  Graph(const int vertexCount = 0);
  //void addIsection(Isection is);
  //void removeIsection(int iSectionId);
  Isection* findIsection(int);
  void addStreet(int iSection1, int iSection2, int weight);
  void createGraph(const char *path); //uses adj matrix stored in a flat file
  //void removeStreet(int streetID);
  void printGraph();
  ~Graph();
 private:
  //Isection *parkingLot;
  //Isection *freeWay;
  int** adjMatrix;
  std::vector <Street*> edgeList;
  std::vector <Isection*> nodeList;
  int vertexCount;
};
    #endif

这是C++,而不是Java或C#。new在这里的工作方式不同。

new表达式返回指针。不能将指向Graph(即Graph*)的指针分配给类型为Graph:的变量

Graph g;
g = new Graph(); // Graph = Graph* ? nope

编译器似乎试图"提供帮助",并且试图使用构造函数take需要int参数来生成类型为Graph的值,但它无法将Graph*转换为int

编写Graph g;时,已经有一个Graph对象。您不需要使用new创建一个。事实上,您甚至可能不希望这样做,因为这会导致内存泄漏。

然后是这一行:

char* path = "graph.csv";

"graph.csv"的类型为char const[10],因此不应将其分配给char*。过去你可以,但结果证明这是个坏主意。该功能被标记为不推荐使用,现在它在C++中被完全删除。你可以:

  • 用它做一个数组:char path[] = "graph.csv";
  • 用正确的类型创建一个指向它的指针:char const* path = "graph.csv";(这很有效,因为数组类型会衰减为指针)

应该是g = Graph();,而忘记g = new Graph;。原因是new向创建的对象(例如Graph*)返回指针,而不是对象值。

更好的是,只执行Graph g;,而忘记为g分配任何内容。这将通过调用Graph的无参数构造函数自动为您创建一个Graph

Graph* g;

它必须是一个指针。

首先,new Graph()返回一个Graph*。在c++中,可以隐式调用带有一个参数的构造函数,因此当前您的代码实际上是有意义的:

g = Graph(new Graph());

你想要的是

g = Graph();