Home  >  Article  >  Backend Development  >  Usage of get and set in c++

Usage of get and set in c++

下次还敢
下次还敢Original
2024-05-01 14:33:16978browse

The get() method is used to obtain the value of the object member variable, and the set() method is used to set the value of the object member variable. The syntax of the get() method is: T get() const; The syntax of the set() method is: void set(T value);

Usage of get and set in c++

Usage of get() and set() in C

The get() and set() methods in C are to access and operate object member variables common methods. They are an important part of the class interface and are used to implement data encapsulation and control access to member variables.

get() method

#get() method is used to get the value of the object member variable. The syntax is:

<code class="cpp">T get() const;</code>

where:

  • T is the data type of the member variable.
  • const keyword indicates that the get() method will not modify the state of the object.

Example:

<code class="cpp">class Person {
private:
    std::string name;

public:
    std::string get_name() const {
        return name;
    }
};

int main() {
    Person person;
    std::string name = person.get_name();
    // ...
}</code>

set() method

set() method Used to set the value of object member variables. The syntax is:

<code class="cpp">void set(T value);</code>

where:

  • T is the data type of the member variable.
  • value is the new value to be set.

Example:

<code class="cpp">class Person {
private:
    std::string name;

public:
    void set_name(const std::string& name) {
        this->name = name;
    }
};

int main() {
    Person person;
    person.set_name("John Doe");
    // ...
}</code>

The above is the detailed content of Usage of get and set in c++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to use getline in c++Next article:How to use getline in c++