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

复习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 @   思wu邪  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
点击右上角即可分享
微信分享提示