Home > Backend Development > C++ > body text

Usage of get and set in c++

下次还敢
Release: 2024-05-01 14:33:16
Original
978 people have browsed it

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>
Copy after login

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>
Copy after login

set() method

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

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

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>
Copy after login

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!

Related labels:
c++
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template