在向量中检索和编辑对象的私有成员 [英] Retrieving and editing private members of objects in a vector

查看:122
本文介绍了在向量中检索和编辑对象的私有成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码添加一些对象到一个向量。然后我想从向量中检索一个特定的对象,并且能够写出和编辑它的私有成员变量。

I have some code which adds a few objects to a vector. I then wish to retrieve a specific object from the vector and be able to both write out and edit its private member variables.

这是我目前的代码: p>

This is the code I currently have:

class Product {
public:
    Product(int n, const string& na, int p)
            : number(n), name(na), price(p) {};
    void info() const;
private:
    string name;
    int number, price;
};

成员函数如下所示:

void Product::info() const {
    cout << number << ". " << name << " " price << endl;
}

然后我创建一个向量并推入一些对象, / p>

I then create a vector and push into it some objects, like so:

vector<Product> range;
range.push_back(Product(1, "Bagpipe", 25));

要检索和列出所有对象的信息,我有以下函数:

To retrieve and list the information about all objects, I have the following function:

void listProducts (const vector<Product>& range1) {
    for_each (range1.begin(), range1.end(), mem_fun_ref(&Product::info));
}

但这是我遇到的地方。

要解决我的问题:我不知道如何从向量中检索单个对象并编辑它们。我需要能够搜索我的向量中包含特定数字或名称的对象,并且能够检索所有其私有成员的信息,也能够编辑所有成员。

To boil my problem down: I have no idea how to retrieve individual objects from the vector and edit them. I need to be able to search my vector for objects containing a specific number or name, and be able to retrieve either the information about all its private members, and also be able to edit all members.

我想要的解决方案是:


  • 函数
    可以返回单个成员

  • to create additional member functions that can return individual members

来创建函数,类似于我已经在上面的函数,可以搜索向量中的每个对象并使用这些附加成员函数的返回值与我正在寻找的内容进行比较

to create functions that, similar to the function I already have above, can search through each object in the vector and use the return from these additional member functions to compare with what I'm looking for

我不太清楚我将如何编辑对象

I don't quite know how I would go about editing an objects private members, but my current guess is that I would need members functions for this as well, and functions that tie in to those

任何帮助将非常感谢!

Any help would be greatly appreciated! Even vague nudges in the right direction!

推荐答案

如果成员变量是私有的,那么根据定义,你不能从外面的世界!您需要执行以下操作之一:

If the member variables are private, then by definition, you cannot access them from the outside world! You will need to do one of the following:


  • 将它们更改为 public

  • 向类添加访问器函数(即 int MyClass :: getFoo()const void MyClass :: setFoo(int))。


  • Change them to public.
  • Add accessor functions to the class (i.e. int MyClass::getFoo() const and void MyClass::setFoo(int)).
  • Make your function a friend of the class.

这与存储在向量无关。

这篇关于在向量中检索和编辑对象的私有成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆