无法使用2d向量成员引用对象

时间:2018-02-08 19:00:36

标签: c++ class vector scope

所以我有一个带有2d矢量成员Board的班级kBoard。我正在尝试使用kBoard访问std::vector::at()的元素 我已经创建了这样的对象:

Board * board = new Board();

然后,我以这种方式访问​​该成员:

board->kBoard.at(pos0).at(pos1);

这里,pos0和pos1是整数 编译器告诉我left of .at must have class/struct/union, type is std::vector<_Ty> [8][8], with _Ty = int

以下是定义class Board的文件:
Board.cpp

#include "Board.h"
Board::Board(void)
{
    for(int i = 0; i < 8; i++)
    {
        for(int j = 0; j < 8; j++)
        {
            kBoard[i][j].assign(1,-1);
        }
    }
}


Board::~Board(void)
{}

Board.h

#pragma once
#include <vector>
class Board
{
public:
    Board(void);
    std::vector<int> kBoard[8][8];
    ~Board(void);
};

现在,当我将kBoard定义为整数数组时,我没有遇到麻烦,但当我意识到,如果我想要绑定检查时,我决定将其设为std::vector<int>我这样做,我需要来自at()的{​​{1}}函数。

这一切对我来说都是正确的,所以我也将完整地粘贴我的主.cpp文件,以防错误实际上源于我的代码中的其他位置。请记住,这段代码并没有真正做任何事情,我只是想在尝试编写其余代码之前修复错误。
Knightstour.cpp

std::vector

KnightsTour.h

#include    "KnightsTour.h"
void main()
{
    using namespace std;
    int xPos, yPos, pos1 = 0, pos0 = 0;
    Board * board = new Board;
    board->kBoard.at(pos0).at(pos1); //issue here
    forward_list<Knight> * route = new forward_list<Knight>;
    route->emplace_front();
    cout << "Knight's starting x position: "; cin >> xPos; xPos -= 1;
    cout << "Knight's starting y position: "; cin >> yPos; yPos -= 1;
    route->begin()->setPos(xPos, yPos);
    route->begin()->setMoves();
    for(int i = 0; i < 8; i++)
    {
        pos0 = route->begin()->moves[i].at(0);
        pos1 = route->begin()->moves[i].at(1);
        if(board->kBoard.at(pos0).at(pos1)) //issue here
            ;
    }
    cout << endl;
    delete route;
    delete board;
    return;
}

1 个答案:

答案 0 :(得分:0)

我实际上错过了2d矢量的正确实现。 像@NathanOliver节目中的评论一样,二维矢量因此被实例化:
std::vector<std::vector<type>> name
我所做的是一组二维矢量。

相关问题