关于传递引用会导致的问题

复习effective c++的时候看到:

于是来验证一下,果然会出现对应问题:

#include <iostream>
#include <vector>
#include <math.h>
#include <algorithm>
#include <unordered_set>
#include <set>
#include <unordered_map>
#include <queue>
using namespace std;

class Student {
public:
    virtual void  print() {
        cout << "this is a Student object" << endl;
    }
};

class subStudent : public Student {
public:
    void print() {
        cout << "this is a subStudent object" << endl;
    }
};



//void validateStudent(const Student& s) {
//    cout << "validateStudent(const Student&) is called" << endl;
//    
//}

void validateStudent(Student s) {
    cout << "validateStudent(Student) is called" << endl;
    s.print(); //虽然被重载了,但是到这里依然会调用父类的print方法
                //因此还是用指针来实现多态好一些?用引用的话会有一些意想不到的问题出现。
}


int main()
{
    subStudent s;
    validateStudent(s);  // 调用了 validateStudent(Student)
    s.print();           // 调用了 Student::print()

	return 0;
}

因此如果想实现多态的话还是使用指针来完成这一目的好一些。

posted @ 2023-04-05 09:36  思wu邪  阅读(14)  评论(0编辑  收藏  举报