メインコンテンツにスキップ
eLearner.app
モジュール 4 · レッスン 1 / 2コース内の 9/18~12 min
モジュールのレッスン (1/2)

クラスとオブジェクト

Object-Oriented Programming (OOP) is a core paradigm of C++. It allows grouping data and functions into single entities called classes.

A class acts as a blueprint, while an object is a concrete instance of that class.

Basic Syntax of a class

In C++, you use the class keyword. Unlike some other languages, in C++, class definitions must end with a semicolon ;:

Code
#include <iostream>
#include <string>

class Player {
    // By default, all members of a class are private
private:
    std::string name;
    int score = 0;

public:
    // Public methods to access or modify private data
    void setName(std::string newName) {
        name = newName;
    }

    void addScore(int points) {
        score += points;
    }

    void display() {
        std::cout << name << " has " << score << " points!" << std::endl;
    }
};

int main() {
    Player p; // Creating an object of type Player
    p.setName("Marco");
    p.addScore(15);
    p.display();
    return 0;
}

Access Specifiers: public and private

Encapsulation consists of hiding the internal implementation details of an object and exposing only a controlled interface.

C++ manages this control using access specifiers:

  • private: members are only accessible inside member functions of the class itself.
  • private is the default access level for classes.
  • public: members are accessible from anywhere outside the class.

Try it yourself

運動#cpp.m4.l1.e1
試行回数: 0読み込み中…

Define a class named Rectangle with two private integer members: width and height. Add a public method void setDimensions(int w, int h) to set them, and a method int getArea() that returns width * height. In main, create a Rectangle, set its dimensions to 5 and 4, and print the area.

エディターを読み込み中…
ヒントを表示

Use the access specifiers `private:`and`public:`. Remember to close the class with a semicolon `;` after the curly brace.

3 回の試行後に解決策が利用可能になります

運動#cpp.m4.l1.e2
試行回数: 0読み込み中…

Define a class named Counter with a private member count initialized to 0. Add public methods void increment() and int getCount(). In main, create a Counter object, increment it twice, and print the value.

エディターを読み込み中…
ヒントを表示

In C++ moderno puoi inizializzare i membri dato direttamente in classe: `int count = 0;`.

3 回の試行後に解決策が利用可能になります