gpt4 book ai didi

c++ Vector在类中声明为私有(private)但具有get函数

转载 作者:行者123 更新时间:2023-11-28 04:04:38 25 4
gpt4 key购买 nike

如果我有一个类,让我们在单独的 .h 文件中这样说

class myclass{
private:
vector<string> data;
public:
vector <string>& getMydata(){
return this->data;
}
};

然后如何在单独的 .cpp 中访问私有(private) vector 中的数据?

最佳答案

.hpp

#include <string>
#include <vector>

class myclass{
private:
std::vector<std::string> data;

public:
// put some data in it when it's default constructed
myclass() : data{"hello", "world"} {}

std::vector<std::string>& getMydata() {
return data;
}
};

main.cpp

#include "the.hpp"
#include <iostream>

int main()
{
myclass instance;

// get reference to the data in the instance
std::vector<std::string>& data_ref = instance.getMydata();

// use the data. data_ref is a reference to exactly the same vector as in "instance"
data_ref.push_back("Someone from the utside was here!");

// check result
std::cout << instance.getMydata()[0] << "\n";
std::cout << instance.getMydata()[1] << "\n";
std::cout << instance.getMydata()[2] << "\n";
}

输出:

hello
world
Someone from the utside was here!

关于c++ Vector在类中声明为私有(private)但具有get函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58964058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com