21xrx.com
2024-04-27 01:01:35 Saturday
登录
文章检索 我的文章 写文章
C++ 构造函数示例
2021-07-08 15:33:37 深夜i     --     --
C + +

C++ 构造函数示例程序:构造函数是名称与类相同的函数。 它们没有返回类型,用于初始化对象。

C++构造器程序示例

#include <iostream>


using namespace std;

class Game {

private:

  int goals;

public:
  // constructor used to initialize
  Game() {
    goals = 0;
  }

  // return score

  int getGoals() {
    return goals;
  }

  // increment goal by one

  void incrementGoal() {
    goals++;
  }
};

int main() {
  Game football;

  cout << "Number of goals when game is started = " << football.getGoals() << endl;

  football.incrementGoal();
  football.incrementGoal();

  cout << "Number of goals a little later = " << football.getGoals() << endl;

  return 0;
}

Game 类包含一个成员目标,用于存储目标数量。 Game() 构造函数用于初始化最初为零的目标数量。 创建游戏类对象足球并在创建对象后立即打印目标数量,并使用 incrementGoal 函数增加目标。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复