关于#派生类#的问题,如何解决?


#include <iostream>
#include <string>
using namespace std;

class Person
{
private:
    string name;
    char sex;
    int age;
public:
    Person(string name1 = "NoName", char sex1 = 'M', int age1 = 0)
    {
        name = name1;
        sex = sex1;
        age = age1;
        cout << "Person()..." << endl;
    }

    ~Person()
    {
        cout << "~Person()..." << endl;
    }
    void print()
    {
        cout << name << "," << sex << "," << age << endl;
    }
};

class Student :public Person
{
private:
    string name;
    char sex;
    int age;
    string school;
    int score;
public:
    Student(string name1, char sex1, int age1, string school1
        , int score1):Person(name1, sex1, age1)
    {
        school = school1;
        score = score1;
        cout << "Student()..." << endl;
    }
    ~Student()
    {
        cout << "~Student()..." << endl;
    }
    void print()
    {
      cout << name << "," << sex << "," << age << endl;
        //Person::print();
        cout << school << "," << score << endl;
    }
};

int main()
{
    Person p1;
    Student wjz("WangJingzhuo", 'M', 19, "HUE", 90);
    p1.print();
    wjz.print();
    return 0;
}

cout << name << "," << sex << "," << age << endl;
这里为什么不报错,可是打印出的是乱码呢。
改成Person::print()就对了。
能详细解释下问题出在哪里吗

这个是二义性问题,你定义了两个print函数,会出现二义性,除了你说的改法,还有一种方法,就是在对象前作用域运算符进行指向,你可以去我主页,基类和派生类博客中我解释了这种情况,也做出了解决方法