C ++矢量向量正在弄乱我

时间:2010-04-27 04:16:02

标签: c++

如果我将此代码放在.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

3 个答案:

答案 0 :(得分:3)

您需要将vector限定为std::vector

它适用于.cpp文件,因为您使用using namespace std;(在头文件中使用using namespace)。

此外,您对成员变量的声明不正确。它应该只是:

myMatrix sudoku_;

如果要设置其尺寸,则需要在构造函数中执行此操作。

答案 1 :(得分:1)

除了限定命名空间外,您还不在头文件中提供sudoku_的构造函数参数。您需要为网格定义自己的构造函数,并在初始化列表中构造sudoku_:

grid::grid() : sudoku_(9,9) { }

答案 2 :(得分:0)

您无法在其声明中初始化sudoku_成员对象。该初始化属于构造函数初始化程序块。