使用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
的无参数构造函数自动为您创建一个Graph
。
Graph* g;
它必须是一个指针。
首先,new Graph()
返回一个Graph*
。在c++中,可以隐式调用带有一个参数的构造函数,因此当前您的代码实际上是有意义的:
g = Graph(new Graph());
你想要的是
g = Graph();
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 错误:未在此范围内声明'reverse'