C++ 如何在c+中通过基类引用访问派生类的对象+;?
我会用C++阅读以下几行:完整的参考书。我没有弄清楚C++ 如何在c+中通过基类引用访问派生类的对象+;?,c++,C++,我会用C++阅读以下几行:完整的参考书。我没有弄清楚 References to Derived Types Similar to the situation as described for pointers earlier, a base class reference can be used to refer to an object of a derived class. The most common application of this is found in function
References to Derived Types
Similar to the situation as described for pointers earlier, a base class reference can be
used to refer to an object of a derived class. The most common application of this is
found in function parameters. A base class reference parameter can receive objects of
the base class as well as any other type derived from that base.
我对以下代码有疑问:
#include<iostream>
using namespace std;
class base
{
protected:
int i;
public:
void seti(int num){i=num;}
int geti(){return i;}
};
class derived:public base
{
protected:
int j;
public:
void setj(int num){j=num;}
int getj(){return j;}
};
void refe(base &ob)
{
ob.seti(1);
ob.setj(2);
}
int main()
{
derived d;
refe(d);
cout<<d.geti();
cout<<"\n"<<d.getj();
return 0;
}
在函数refe()((派生*)ob.setj(2)中,我也像这样强制转换;这还显示以下错误:
D:\Users\srilakshmikanthan.p\Documents\source code\ex.cpp||In function 'void refe(base&)':|
D:\Users\srilakshmikanthan.p\Documents\source code\ex.cpp|28|error: 'class base' has no member named
'setj'
=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 5 second(s)) ===
D:\Users\srilakshmikanthan.p\Documents\source code\ex.cpp||In function 'void refe(base&)':|
D:\Users\srilakshmikanthan.p\Documents\source code\ex.cpp|28|error: invalid cast from type 'base' to
type 'derived*'
=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 3 second(s)) ===|
所以请在那本书中解释这几行。您只能从基类引用中调用派生类的虚函数。请看这个
#include<iostream>
class Base
{
public:
virtual void fun()
{
std::cout<<"Base";
}
};
class Derived:public Base
{
public:
void fun()override
{
std::cout<<"Derived";
}
};
void myfun(Base &ob)
{
ob.fun();
}
int main()
{
Derived ob;
myfun(ob);
return 0;
}
在函数refe()((派生*)ob.setj(2)中,我也像这样强制转换;这还显示以下错误:
D:\Users\srilakshmikanthan.p\Documents\source code\ex.cpp||In function 'void refe(base&)':|
D:\Users\srilakshmikanthan.p\Documents\source code\ex.cpp|28|error: 'class base' has no member named
'setj'
=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 5 second(s)) ===
D:\Users\srilakshmikanthan.p\Documents\source code\ex.cpp||In function 'void refe(base&)':|
D:\Users\srilakshmikanthan.p\Documents\source code\ex.cpp|28|error: invalid cast from type 'base' to
type 'derived*'
=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 3 second(s)) ===|
转换为
((派生和)ob).setj(2)代码>这将起作用,因为它不是指针,而是参考要使多态性发挥作用,您需要使用虚拟
函数。在子类中重写这些函数,而不是创建新函数。至于cast,首先,C风格的cast应该被看作是一个警告,表明您做错了什么。其次,在refe
函数中,ob
是引用而不是指针,因此需要将其转换为引用(如static\u cast(ob)
),这意味着对派生类的引用可以隐式转换为对基类的引用。这并不意味着您可以使用对基类的引用来访问派生类的成员。要通过基类引用调用派生行为,必须使用virtual
语义,或者将引用转换回对派生类的引用。