如何通过C ++中的基类引用访问派生类的对象?

时间:2019-12-03 10:37:41

标签: c++

我将阅读C ++中的以下几行:完整的参考书。我对此一无所知。

#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;
}

我对以下代码有疑问:

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)) ===|

并且我也在函数refe()((derived *)ob).setj(2);中这样转换这也显示以下错误:

$Rusers = Get-WinEvent  -Computer dc02 -FilterHashtable @{Logname='Security';ID=4672} -MaxEvents 50 |
 `   select @{N='User';E={$_.Properties[1].Value}},TimeCreated

$DAUsers = Get-ADGroupMember -Identity "Domain Admins"

Foreach ($DAUser in $DAUsers){
$DomainUser = $DAUser.SamAccountName

foreach ($Ruser in $Rusers){
$RAUser = $Ruser.User

If ($RAUser -match $DomainUser){
Write-Host $Ruser is domain admin }
}[![enter image description here][1]][1]
}

所以请在那本书中解释这一行。

1 个答案:

答案 0 :(得分:0)

您只能从基类参考中调用派生类的虚函数,参见

#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;
}

输出:

Derived
Process returned 0 (0x0)   execution time : 0.266 s
Press any key to continue.

我也在函数refe()((derived *)ob).setj(2);中这样转换这也显示以下错误:

投射到((derived &)ob).setj(2);可以正常工作,因为它不是指针,而是引用