关于传递引用会导致的问题
复习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;
}
因此如果想实现多态的话还是使用指针来完成这一目的好一些。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)