看到书上的代码之后,产生了一些疑问,还请大佬指教一下
程序如下:
#include<iostream>
using namespace std;
class Base1{
public:
virtual void display()const;
};
void Base1::display()const{
cout<<"Base1::display()"<<endl;
}
class Base2:public Base1{
public:
void display()const;
};
void Base2::display()const{
cout<<"Base2::display()"<<endl;
}
class Derived:public Base2{
public:
void display()const;
};
void Derived::display()const{
cout<<"Derived::display()"<<endl;
}
void fun(Base1 *ptr){
ptr->display();
}
int main()
{
Base1 base1;
Base2 base2;
Derived derived;
fun(&base1);
fun(&base2);
fun(&derived);
return 0;
}
这是书上讲虚函数的时候的那道例题
………………………………………………………………………………………………………………………………………………………………………………………………………………
第一个疑问:
我把虚函数去掉,想试用一下赋值兼容规则,程序变成了下面的样子
#include<iostream>
using namespace std;
class Base1{
public:
void display()const;
};
void Base1::display()const{
cout<<"Base1::display()"<<endl;
}
class Base2:public Base1{
public:
void display()const;
};
void Base2::display()const{
cout<<"Base2::display()"<<endl;
}
class Derived:public Base2{
public:
void display()const;
};
void Derived::display()const{
cout<<"Derived::display()"<<endl;
}
void fun(Base1 *ptr){
ptr->display();
}
int main()
{
Base1 base1;
Base2 base2;
Derived derived;
fun(&base1);
fun(&base2);
fun(&derived);
return 0;
}
但是呐,运行结果不尽人意
因为呐,书上将赋值兼容规则的时候是把display()声明为内联函数的,这里我就不是很明白为什么会这样了……还请大佬指导一下
……………………………………………………………………………………………………………………………………………………………………………………………………
第二个问题
我把第12行和14行的const去掉了
#include<iostream>
using namespace std;
class Base1{
public:
virtual void display()const;
};
void Base1::display()const{
cout<<"Base1::display()"<<endl;
}
class Base2:public Base1{
public:
virtual void display ();
};
void Base2::display(){
cout<<"Base2::display()"<<endl;
}
class Derived:public Base2{
public:
void display()const ;
};
void Derived::display()const{
cout<<"Derived::display()"<<endl;
}
void fun(Base1 *ptr){
ptr->display();
}
int main()
{
Base1 base1;
Base2 base2;
Derived derived;
fun(&base1);
fun(&base2);
fun(&derived);
return 0;
}
结果就变化了……这个也请大佬讲解一下