访问Vector的元素- c++

Access Elements of Vector - C++

本文关键字:c++ 元素 Vector 访问      更新时间:2023-10-16

我有以下类:

class Friend
{
public:
    Friend();
    ~Friend(){}
    void setName(string friendName){ name = friendName; }
    void setAge(int friendAge) { age = friendAge; }
    void setHeight(int friendHeight) { height = friendHeight; }
    void printFriendInfo();
private:
    string name;
    int age;
    float height;
};
//implementations
Friend::Friend()
{
    age = 0;
    height = 0.0;
}
//printing
void Friend::printFriendInfo()
{
    cout << "Name       : " << name << endl;
    cout << "Age        : " << age << endl;
    cout << "Height     : " << height << endl << endl;
}

现在我可以在一个向量中引入值,像这样:

std::vector<Friend> regist(4, Friend());
regist[1].setAge(15);
regist[1].setHeight(90);
regist[1].setName("eieiei");
regist[2].setAge(40);
regist[2].setHeight(85);
regist[2].setName("random");

在调试中,这个解决方案工作得很好。但是现在我试着打印这个向量。到目前为止还没有成功。

for (int i = 0; i < regist.size(); i++) {
        cout << regist[i]; //<-- error here
        cout << 'n';
    }

你可以重新设计一点(本质上):

#include <iostream>
class Friend
{
public:
    Friend();
    // A more general name, const, and taking a stream.
    void write(std::ostream&) const;
private:
    std::string name;
    int age;
    float height;
};
Friend::Friend()
{
    age = 0;
    height = 0.0;
}
void Friend::write(std::ostream& stream) const
{
    stream << "Name       : " << name << std::endl;
    stream << "Age        : " << age << std::endl;
    stream << "Height     : " << height << std::endl << std::endl;
}
// Forward to the member function
inline std::ostream& operator << (std::ostream& stream, const Friend& object) {
    object.write(stream);
    return stream;
}
int main() {
    Friend f;
    std::cout << f;
}

直接调用printFriendInfo()成员函数:

for (int i = 0; i < regist.size(); i++) {
        regist[i].printFriendInfo();
    }

For

    cout << regist[i];

工作,在Friend

中添加一些访问函数
string getName() const { return name; }
int getAge() const { return age; }
float getHeight() const { return height; }

和实现一个重载的operator<<函数:

std::ostream& operator<<(std::ostream& out, Friend const& f)
{
    out << "Name       : " << f.getName() << std::endl;
    out << "Age        : " << f.getAge() << std::endl;
    out << "Height     : " << f.getHeight() << std::endl;
    return out;
}