从数组中检索对象的值
Retrieving values of an object from an array?
原谅这个例子,但是在这个例子中:
#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
相关文章:
- 如何检索由带通配符的字符串索引的对象
- 用于从可能不存在的容器中检索对象的 API 设计
- 在 c++ 中使用指向对象的指针检索数据
- 通过 std::bind 从对象成员检索值
- 将 JSON 对象作为参数在 JNI 中传递给 CPP,并在 CPP 中检索 JSON 对象的数据
- C++ 从树中检索对象
- 检索不同类型的对象指针
- 如何在Boost Serialization中检索多个对象值
- 使用Boost序列化保存和检索多个对象
- C++ 无法检索自定义矢量中的对象
- 如何通过先前存储的ID从结构对象中检索值?C
- 在另一个中检索JSON对象
- c++使用字符串句柄对对象进行通用存储和检索
- 从C 添加和检索类的对象
- 如何从wow64进程中检索特定内核对象的64位地址
- 检索在函数内部使用运算符new分配的类指针对象成员的值时出现的问题
- 从数据库中以 blob 数据类型形式存储的原始图像数据中检索 CImage 对象
- QML:如何检索默认字体对象
- 从继承的对象检索信息
- 从 win32api C++中的 LDAPMessage 对象检索'pre windows 2000 logon'名称