0

我正在 Qt 环境中学习 C++,并且正在在线浏览其中的示例代码。谁能给我解释一下这个语法?

const TicTacToe * GetTicTacToe() const { return m_tictactoe.get(); }

为什么const函数的左括号前有一个?是指针还是乘法?

完整的类如下,但上面提到的指令的语法我不清楚

class QtTicTacToeWidget : public QWidget
 {
   Q_OBJECT
   public:
      explicit QtTicTacToeWidget(QWidget *parent = 0);
      const TicTacToe * GetTicTacToe() const { return m_tictactoe.get(); }
      void Restart();
4

2 回答 2

1

第一个 const 表示变量指针TicTacToe不能更改。函数声明后的第二个常量表示该函数内部发生的任何事情都不会改变类内部的任何成员变量。因为它实际上不会更改类上的内存数据,所以当您使用该类的任何常量对象时都可以使用它。例如:

const QtTicTacToeWidget myConstObject;
// Since myConstObject is a constant, I am not allowed to change anything inside
// the class or call any functions that may change its data.  A constant function
// is a function that does not change its own data which means I can do this:
myConstObject.GetTicTacToe();

// But I can not do the next statement because the function is not constant
// and therefore may potentially change its own data:
myConstObject.Restart();
于 2013-08-08T22:18:57.893 回答
0

左括号前的 const 表示该函数是 const 成员函数。它本质上说它保证不修改类,因此可以在声明为 const 的对象上调用。

好吧,它还允许函数修改 const 类中的可变变量。

于 2013-08-08T22:18:14.890 回答