C++ 预期的id表达式-使用g++;
我刚刚编写了一个程序,在C++ 预期的id表达式-使用g++;,c++,C++,我刚刚编写了一个程序,在main.cpp文件中有一个Matrix对象。一切都很好 现在我想将对象外包到Matrix.cpp文件和Matrix.h头文件中,但我遇到了一个错误 我发现以下编译器错误: Matrix.cpp:5:15:错误:在“(”标记之前应该有id表达式 矩阵::矩阵(int n_行){ 矩阵h: #ifndef Matrix #define Matrix #include "iostream" #include "string" #include <sstream>
main.cpp
文件中有一个Matrix
对象。一切都很好
现在我想将对象外包到Matrix.cpp
文件和Matrix.h
头文件中,但我遇到了一个错误
我发现以下编译器错误:
Matrix.cpp:5:15:错误:在“(”标记之前应该有id表达式
矩阵::矩阵(int n_行){
矩阵h:
#ifndef Matrix
#define Matrix
#include "iostream"
#include "string"
#include <sstream>
#include <cstdlib>
using namespace std;
class Matrix{
private:
int n_rows;
int* vect;
public:
Matrix(int);
};
#endif
#ifndef矩阵
#定义矩阵
#包括“iostream”
#包括“字符串”
#包括
#包括
使用名称空间std;
类矩阵{
私人:
int n_行;
int*vect;
公众:
矩阵(int);
};
#恩迪夫
Matrix.cpp:
#include "Matrix.h"
// Constructor
Matrix::Matrix(int n_rows){ //ERROR
if(n_rows>0){
this->n_rows = n_rows;
this->vect = new int[n_rows];
srand(time(NULL));
for(int i = 0; i< n_rows; i++){
this->vect[i] = rand() % 100;
}
}
}
#包括“Matrix.h”
//建造师
矩阵::矩阵(int n_行){//错误
如果(n_行>0){
此->n_行=n_行;
此->向量=新整数[n_行];
srand(时间(空));
对于(int i=0;i向量[i]=rand()%100;
}
}
}
也许这个问题有一个关键词我不知道。如果你能帮助我,我将不胜感激
新:基于已接受的答案:为什么出现的矩阵
会被一个空格取代?\define Matrix
意味着预处理器会将每次出现的“矩阵”替换为零
因此,编译器可以看到
using namespace std;
class {
private:
int n_rows;
int* vect;
public:
(int);
};
::(int n_rows){
if(n_rows>0){
this->n_rows = n_rows;
this->vect = new int[n_rows];
srand(time(NULL));
for(int i = 0; i< n_rows; i++){
this->vect[i] = rand() % 100;
}
}
}
#define Matrix
意味着预处理器会将每次出现的“Matrix”替换为零
因此,编译器可以看到
using namespace std;
class {
private:
int n_rows;
int* vect;
public:
(int);
};
::(int n_rows){
if(n_rows>0){
this->n_rows = n_rows;
this->vect = new int[n_rows];
srand(time(NULL));
for(int i = 0; i< n_rows; i++){
this->vect[i] = rand() % 100;
}
}
}
在标题顶部定义一个预处理器常量
矩阵
,然后对类名重新使用相同的标识符。应将预处理器常量重命名为例如矩阵_H
或类似名称。不是问题,而是包含“iostream”#包含“string”
应该是#include#include
Ty NathanOliver,我会考虑到这一点。幸运的是,我也有同样的问题,即使在将include从一个矩阵重命名为另一个矩阵后,错误消息仍然显示编译器的完整输出?粘贴副本?没有“信息”消息?没有其他任何信息(可能看起来不相关,但可能不是)?在标题顶部定义一个预处理器常量矩阵
,然后对类名重新使用相同的标识符。您应该将预处理器常量重命名为例如矩阵H
或类似。不是问题,而是包括“iostream”包括“string”
应该是#include#include
Ty NathanOliver,我会考虑到这一点。幸运的是,我也有同样的问题,即使在将include从一个矩阵重命名为另一个矩阵后,错误消息仍然显示编译器的完整输出?粘贴副本?没有“信息”消息?没有其他任何信息(这可能看似无关,但可能并非如此)?当我将标题从Matrix.h重命名为Matrix.h时,它开始编译,这有什么意义吗?Ty@PabloJeken您不应该重命名标题,您应该重命名include guard。我重命名了,但它没有更改任何内容。另外,重命名标题解决了错误。@PabloJeken请看一看,它是在我重命名标题时开始编译的从Matrix.h到Matrix.h的标题,这有什么意义吗?Ty@PabloJeken您不应该重命名标题,您应该重命名include guard。我重命名了,但它没有改变任何东西。另外重命名标题解决了错误。@PabloJeken请看一看