【问题标题】:Question regarding to char* function member function in class关于类中 char* 函数成员函数的问题
【发布时间】:2020-12-02 16:46:42
【问题描述】:

我正在尝试从 Udacity 学习 c++。我需要澄清一下我的理解是否正确。所以代码如下。

井字游戏:

class Board
{//the class tracks the game and the winner
    char positionsSelected[16];
    char winner;
    
public:
    //Constructor
    Board();
    int setPosition(int gridNumber, char user);
    char* getPositions(void);
};

char* getPositions(void)
    {//return all the positions on the board
        return positionsSelected;
    }

如果你看一下,成员函数char* getPositions(void) 是在类中声明的。

我知道假设可能真的很糟糕,但这就是我的思考过程和问题

  1. 由于您基本上是在阅读一系列字符,所以它必须是 char*

  2. 为什么getPositions(void)的参数一定要?可以和空括号()一样吗?

  3. 如果函数原型是char* getPositions(),是否意味着它返回了指针?我可以假设char*getPosition(void) 的返回值指向char array(positionsSelected)

  4. 如果我对 3 的假设是错误的。我可以这样写吗

char* getPositions(void){
    char* pointers;
    pointers = positionSelected;
    return pointers;
}

任何建议或解释将不胜感激。

【问题讨论】:

  • 无关:知道获胜者不是我要为井字游戏板分配的责任。对我来说,board 应该代表棋盘,并且完全不知道游戏逻辑。
  • 请注意,通过在没有保护的情况下返回positionsSelectedgetPositions 的调用者可以做任何他们想做的事情。与其将整个游戏板开放给公众监督,不如拥有char get_position(int x, int y) 之类的功能,并且一次只允许用户看到一个角色。这样,游戏板的真实性质仍然是encapsulated。您可以完全重写棋盘的内脏,没有人会知道它现在将棋盘存储在魔法仙尘云中。

标签: c++ arrays class pointers


【解决方案1】:
  1. 由于您基本上是在读取一个字符序列,所以它必须是 char*。

最好将成员设为std::string positionsSelected;。然后你可以从你的方法中返回std::string const &。这样使用起来更安全、更简单。

  1. 为什么getPositions(void)的参数必须要?可以和空括号()一样吗?

由于来自 C 的包袱,这两种语法都被接受,它们可能意味着不同的东西:

  • void foo(void); 明确指定不接受任何参数。
  • void foo(); 没有指定接受哪些参数。

在 C++ 中,它们的含义相同:不接受任何参数。空括号是首选语法 (char * getPositions();)。

  1. 如果函数原型是char* getPositions(),是否意味着它返回了指针?我可以假设 char*getPosition(void) 的返回值指向 char array(positionsSelected)。

是的,你可以做这个假设。数组隐式衰减为指向第一个元素的指针。

【讨论】:

  • "最好将成员设为std::string positionsSelected;。然后您可以从您的方法中返回std::string const &。这样更安全,更易于使用。" -或者,std::array<char, 16> 而不是std::string,那么您就没有动态内存分配的开销。
猜你喜欢
  • 2020-01-30
  • 2010-10-08
  • 2020-04-02
  • 2017-12-08
  • 2010-10-01
  • 2010-12-23
  • 1970-01-01
  • 2012-10-08
  • 1970-01-01
相关资源
最近更新 更多