溫馨提示×

C++中如何使用set和get方法

c++
小樊
81
2024-09-25 01:34:16
欄目: 編程語言

在 C++ 中,setget 方法通常用于封裝對數(shù)據(jù)成員的訪問。set 方法用于設(shè)置數(shù)據(jù)成員的值,而 get 方法用于獲取數(shù)據(jù)成員的值。這些方法可以確保數(shù)據(jù)的完整性和安全性,同時提供一種統(tǒng)一的接口來訪問數(shù)據(jù)成員。

以下是一個簡單的示例,展示了如何在類中使用 setget 方法:

#include <iostream>
#include <string>

class Person {
private:
    std::string name;
    int age;

public:
    // set 方法
    void setName(const std::string& newName) {
        name = newName;
    }

    void setAge(int newAge) {
        if (newAge >= 0 && newAge <= 150) {
            age = newAge;
        } else {
            std::cerr << "Invalid age!" << std::endl;
        }
    }

    // get 方法
    std::string getName() const {
        return name;
    }

    int getAge() const {
        return age;
    }
};

int main() {
    Person person;
    person.setName("Alice");
    person.setAge(30);

    std::cout << "Name: " << person.getName() << std::endl;
    std::cout << "Age: " << person.getAge() << std::endl;

    return 0;
}

在上面的示例中,我們定義了一個 Person 類,其中包含兩個私有數(shù)據(jù)成員 nameage。然后,我們?yōu)檫@兩個數(shù)據(jù)成員提供了 setget 方法。setName 方法接受一個 std::string 類型的參數(shù),用于設(shè)置 name 的值。setAge 方法接受一個整數(shù)參數(shù),用于設(shè)置 age 的值,并在設(shè)置之前檢查輸入值是否在有效范圍內(nèi)(例如,0 到 150)。getNamegetAge 方法分別用于獲取 nameage 的值,它們都是 const 方法,因此不會修改對象的狀態(tài)。

main 函數(shù)中,我們創(chuàng)建了一個 Person 對象,并使用 set 方法設(shè)置了其 nameage 的值。然后,我們使用 get 方法獲取這些值,并將它們輸出到控制臺。

0