简体   繁体   中英

Print an array consisting of string and integer without using function in cpp file

I have this code in .cpp file and I'm not allowed to edit the code in this file .

#ifndef CP_MEMBER_H
#define CP_MEMBER_H
#include <iostream>
#include <string>

class CP_Member
{
public:
    string m_name;
    int m_age;

public:
    CP_Member() {
        m_name = "?";
        m_age = 0;
    }
    CP_Member(string name, int age) : m_name(name), m_age(age) {}
    friend ostream& operator<< (ostream& os, const CP_Member& a);
};

ostream& operator<< (ostream& os, const CP_Member& a) {
    os << "Name:" << a.m_name << " Age: " << a.m_age;
    return os;
}

#endif
#pragma once

I've only written these on my .h file.

Since the main file is already doing

cout << newCommers[i] << endl;

You just have to make sure it does what you want. Since newCommers[i] is a CP_Member , you control everything about it, including what happens when you use operator<< on it. How to control this should be in your lecture notes, and you can research the problem with "overloading operator<<".

You need to define a friend ostream& operator<< because that's being used in cout statement:

friend ostream& operator<<(ostream &out, const CP_Member &mem)
{
  return out << "Name: " << mem.m_name << " Age: " << mem.m_age;
}

After that, the program outputs:

Zhang San 22
Li Si 19
Wang Wu 18
Zhao Liu 24
? 0

Aside, you could use initialization list to construct:

CP_Member(string name, int age) : m_name(name), m_age(age) {
  std::cout << "Object constructed."; // Optional syntax
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM