为什么指针s可以看到fun3()方法,请各位大虾指教!!!
时间:2011-11-29
来源:互联网
#include <iostream>
using namespace std;
class Person
{
public:
void fun1()
{
cout << "fun1()" << endl;
}
void fun2()
{
cout << "fun2()" << endl;
}
};
class Student : public Person
{
public:
void fun1()
{
cout << "refun1()" << endl;
}
void fun3()
{
cout << "fun3()" << endl;
}
};
int main()
{
Student *s;
Person *p = new Person();
s = (Student *)p;
s->fun1();
s->fun2();
s->fun3();
return 0;
}
using namespace std;
class Person
{
public:
void fun1()
{
cout << "fun1()" << endl;
}
void fun2()
{
cout << "fun2()" << endl;
}
};
class Student : public Person
{
public:
void fun1()
{
cout << "refun1()" << endl;
}
void fun3()
{
cout << "fun3()" << endl;
}
};
int main()
{
Student *s;
Person *p = new Person();
s = (Student *)p;
s->fun1();
s->fun2();
s->fun3();
return 0;
}
作者: Strive_For_You 发布时间: 2011-11-29
其实这种写法是错误的,不过fun3()没有用到class Student的其他成员变量所以没报错。
fun3()是非虚拟函数,这种方法调用fun3()其实等于fun3(s)(调用类方法其实是把对象作为参数),由于fun3()没有用到p所指向的对象,所以没出错。
fun3()是非虚拟函数,这种方法调用fun3()其实等于fun3(s)(调用类方法其实是把对象作为参数),由于fun3()没有用到p所指向的对象,所以没出错。
作者: lhylhy 发布时间: 2011-11-29
这些如果弄懂了C++对象模型就知道了。
作者: lhylhy 发布时间: 2011-11-29
Student *s; 因为你是 Student 指针啊,不过你这么滴是会出错的,
Student 构造不会调用的。
指针只关心类型,不关心内存里面塞什么,你就是等了个int内存 也可以调。
Student 构造不会调用的。
指针只关心类型,不关心内存里面塞什么,你就是等了个int内存 也可以调。
作者: jptaozhantaozhan 发布时间: 2011-11-29
输出结果为:
refun1()
fun2()
fun3()
不太清楚为什么,关注
refun1()
fun2()
fun3()
不太清楚为什么,关注
作者: LarRadion 发布时间: 2011-11-29
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28