簡體   English   中英

使用g ++編譯主模塊時發生奇怪的錯誤

[英]strange error compiling main module using 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*’

這是我要編譯的主要模塊,下面是我在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的no-arg構造函數自動為您創建一個Graph

Graph* g;

它必須是一個指針。

首先, new Graph()返回Graph* 在c ++中,可以隱式調用帶有一個參數的構造函數,因此當前您的代碼確實有意義:

g = Graph(new Graph());

你想要的是什么

g = Graph();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM