【问题标题】:Having some issues attempting to define a variable in a separate class - use to working with one.尝试在单独的类中定义变量时遇到一些问题 - 习惯于使用一个。
【发布时间】:2015-12-23 01:19:36
【问题描述】:

我正在尝试使用 OOP 制作井字游戏,但我遇到了问题。当试图制作一个总共有 9 个方格并且所有方格都为空的游戏板时,我执行以下操作。

主要

#include "stdafx.h"

#include <vector>

int main()
{

    char empty = ' '; //Empty square on playing board
    const int numbOfSquares = 9; //Total amount of squares on board
    std::vector<char> board(numbOfSquares, empty); // The playing board

    return 0;
}

在我的董事会课程中,我正在尝试做同样的事情,但它的工作方式不同。

Board.h

#pragma once
#include <vector>

class Board
{
private:
    const char empty = ' '; //Empty square on game board
    const int numbOfSquares = 9; //Number of squares on the board
    std::vector<char> board(numbOfSquares, empty); //The playing board
public:

};

说“numbOfSquares”和“empty”不是类型名称时发生错误。我想我理解这个错误信息,但我不确定如何解决它。我可以 - 重载,是这个术语 - 成员函数中的 board 变量吗?

我完全不知道该怎么做,希望得到一些帮助。感谢您的时间。

【问题讨论】:

    标签: c++ oop console-application


    【解决方案1】:

    std::vector&lt;char&gt; board(numbOfSquares, empty); 在指定您的班级成员列表时是不允许的。相反,您应该使用构造函数初始化列表:

    Board(): board(numbOfSquares, empty)
    {
    }
    

    所有成员都可以这样初始化。例如,您的const int numbOfSquares = 9; 行是写作的捷径:

    Board(): numbOfSquares(9)
    {
    }
    

    但是,对于需要在括号中提供构造函数参数的情况,没有这样的捷径。

    一种将构造函数参数作为花括号初始化器列表提供的快捷方式,但是对于vector 避免这样做是明智的,因为向量更愿意将花括号的内容视为列表向量的初始值,而不是构造函数参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-25
      • 2021-05-04
      • 2022-10-01
      • 2020-05-14
      • 2015-01-11
      • 1970-01-01
      相关资源
      最近更新 更多