使用g ++编译主模块的奇怪错误

ajk*_*jkl 2 c++ g++

我试图使用"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*’
Run Code Online (Sandbox Code Playgroud)

这是我正在尝试编译的主要模块,下面是我在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;
}
Run Code Online (Sandbox Code Playgroud)

这是我的Graph类

    /*
 * 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
Run Code Online (Sandbox Code Playgroud)

R. *_*des 5

这是C++,而不是Java或C#.new这里的工作方式不一样.

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

Graph g;
g = new Graph(); // Graph = Graph* ? nope
Run Code Online (Sandbox Code Playgroud)

好像编译器试图"有用"并试图使用你的构造函数take接受一个int参数来创建一个类型的值Graph,但它不能将a转换Graph*int.

当你写作Graph g;已经有一个Graph对象.您不需要创建一个new.事实上,您可能甚至不想这样做,因为它会导致内存泄漏.

那就是这一行:

char* path = "graph.csv";
Run Code Online (Sandbox Code Playgroud)

"graph.csv"有类型,char const[10]所以你不应该将它分配给char*.在过去,你可以,但结果是一个坏主意.该功能已标记为已弃用,现在已在C++中完全删除.而不是这样做,你可以:

  • 用它做一个数组:char path[] = "graph.csv";;
  • 使用正确的类型指向它:( char const* path = "graph.csv";这是因为数组类型衰减到指针);

  • 我想整天在Objective-C上工作正在摧毁我的大脑. (3认同)