溫馨提示×

能否用C++的set和get實(shí)現(xiàn)數(shù)據(jù)封裝

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

當(dāng)然可以。在C++中,我們可以使用setget方法來實(shí)現(xiàn)數(shù)據(jù)封裝,保護(hù)類的內(nèi)部數(shù)據(jù)不被外部直接訪問。以下是一個簡單的示例:

#include <iostream>
#include <set>
#include <string>

class DataWrapper {
private:
    std::set<std::string> data;

public:
    // 添加數(shù)據(jù)到set中
    void addData(const std::string& data) {
        this->data.insert(data);
    }

    // 從set中獲取數(shù)據(jù)
    std::string getData(const std::string& key) const {
        auto it = data.find(key);
        if (it != data.end()) {
            return *it;
        } else {
            return ""; // 如果找不到數(shù)據(jù),返回空字符串
        }
    }
};

int main() {
    DataWrapper dw;
    dw.addData("Hello");
    dw.addData("World");

    std::cout << "Data: " << dw.getData("Hello") << std::endl;
    std::cout << "Data: " << dw.getData("World") << std::endl;
    std::cout << "Data: " << dw.getData("Not exist") << std::endl;

    return 0;
}

在這個示例中,我們創(chuàng)建了一個名為DataWrapper的類,它包含一個std::set<std::string>類型的私有成員變量data。我們提供了兩個公共成員函數(shù)addDatagetData,分別用于向data中添加數(shù)據(jù)和從data中獲取數(shù)據(jù)。這樣,我們就可以保護(hù)類的內(nèi)部數(shù)據(jù)不被外部直接訪問,實(shí)現(xiàn)了數(shù)據(jù)封裝。

0