如果我将此代码放入 .cpp 文件中并运行它,它运行得很好:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
typedef vector<int> row;
typedef vector<row> myMatrix;
void main()
{
//cout << endl << "test" << endl;
myMatrix mat(2,2);
mat[0][1] = 2;
cout << endl << mat[0][1] << endl;
}
但是,如果我像这样用 .h 文件制作一个 .h 和一个 .cpp 文件,它会给我一大堆错误。
#ifndef _grid_
#define _grid_
#include<iostream>
#include<vector>
#include<string>
using namespace std;
typedef vector<int> row;
typedef vector<row> myMatrix;
class grid
{
public:
grid();
~grid();
int getElement(unsigned int ri, unsigned int ci);
bool setElement(unsigned int ri, unsigned int ci, unsigned int value);
private:
myMatrix sudoku_(9,9);
};
#endif
这些是我得到的一些错误:
warning C4091: 'typedef ' : ignored on left of 'int' when no variable is declared
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
最佳答案
您需要将 vector
限定为 std::vector
。
它在 .cpp 文件中有效,因为您使用 using namespace std;
(不要在头文件中使用 using namespace
)。
此外,您对成员变量的声明不正确。它应该只是:
myMatrix sudoku_;
如果你想设置它的维度,你需要在构造函数中这样做。
关于 vector 的 C++ Vector 搞乱了我,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2718689/