W
wfhsiao
Hello,
while refreshing my understanding of C++, I found the overloaded
operators could not work properly. Why my following codes keep printing
the student b's data as a person's? Did I lost anything? Thanks for
your help!
person a("John", 30);
student b("Mary", 20, "93406001");
person *p[2] = {&a, &b};
for (int j=0; j<2; j++)
cout << (*p[j]+3) << endl;
The definitions of person and student are listed below.
--------------------------------
class person
{
private:
string name;
int age;
public:
person(string na, int ag):name(na), age(ag) {}
person operator+(int n) const
{
return person(name, age+n);
}
virtual void print(ostream& os) const
{
os << name << " " << age;
}
};
ostream& operator<< (ostream& os, const person &aP)
{
aP.print(os);
return os;
}
-----------------------------------
class studentublic person
{
private:
string studentNo;
public:
student(string na, int ag, string sno)erson(na, ag), studentNo(sno)
{}
void print(ostream &os) const
{
os << studentNo << " ";
person:rint(os);
}
};
while refreshing my understanding of C++, I found the overloaded
operators could not work properly. Why my following codes keep printing
the student b's data as a person's? Did I lost anything? Thanks for
your help!
person a("John", 30);
student b("Mary", 20, "93406001");
person *p[2] = {&a, &b};
for (int j=0; j<2; j++)
cout << (*p[j]+3) << endl;
The definitions of person and student are listed below.
--------------------------------
class person
{
private:
string name;
int age;
public:
person(string na, int ag):name(na), age(ag) {}
person operator+(int n) const
{
return person(name, age+n);
}
virtual void print(ostream& os) const
{
os << name << " " << age;
}
};
ostream& operator<< (ostream& os, const person &aP)
{
aP.print(os);
return os;
}
-----------------------------------
class studentublic person
{
private:
string studentNo;
public:
student(string na, int ag, string sno)erson(na, ag), studentNo(sno)
{}
void print(ostream &os) const
{
os << studentNo << " ";
person:rint(os);
}
};