从数组中检索对象的值

Retrieving values of an object from an array?

本文关键字:对象 检索 数组      更新时间:2023-10-16

原谅这个例子,但是在这个例子中:

#include <iostream>
#include <string>
using namespace std;
class A { 
private:
    string theName;
    int theAge;
public:
    A() : theName(""), theAge(0) { }
    A(string name, int age) : theName(name), theAge(age) { }
};
class B {
private:
    A theArray[1];
public:
    void set(const A value) {theArray[0] = value; }
    A get() const { return theArray[0]; } 
};
int main()
{
    A man("Bob", 25);
    B manPlace;
    manPlace.set(man);
    cout << manPlace.get();
    return 0;
}

当我调用manPlace.get()时,我是否可以在main中检索"man"对象的内容?我的目的是在调用manPlace.get()时打印姓名(Bob)和年龄(25)。我想在另一个类中的数组中存储一个对象,我可以在main中检索所述数组的内容。

您需要在您的a类上定义ostream::operator<<来完成此操作-否则,如何将年龄和姓名生成为文本输出的格式是未定义的(并且它们是您的a类的私有成员)。

看一下ostream::operator<<的引用。对于A类,这样的操作符可以这样定义:

std::ostream& operator<< (std::ostream &out, A &a) {
  out << "Name: " << a.theName << std::endl;
  out << "Age: " << a.theAge << std::endl;
  return out;
}

输出如下:

Name: XX
Age: YY
所以你的完整代码应该是:
#include <iostream>
#include <string>
using namespace std;
class A {
private:
  string theName;
  int theAge;
public:
  A() : theName(""), theAge(0) { }
  A(string name, int age) : theName(name), theAge(age) { }
  friend std::ostream& operator<< (std::ostream &out, A &a) {
    out << "Name: " << a.theName << std::endl;
    out << "Age: " << a.theAge << std::endl;
    return out;
  }
};
class B {
private:
  A theArray[1];
public:
  void set(const A value) { theArray[0] = value; }
  A get() const { return theArray[0]; }
};
int main()
{
  A man("Bob", 25);
  B manPlace;
  manPlace.set(man);
  cout << manPlace.get();
  return 0;
}

将输出:

Name: Bob
Age: 25