gpt4 book ai didi

c++ - C++ 中的向上转型是否允许访问父级的私有(private)成员或 friend

转载 作者:行者123 更新时间:2023-11-28 05:46:55 25 4
gpt4 key购买 nike

根据我在类里面学到的知识,派生类不继承其父类的:

  • 构造函数/析构函数
  • friend
  • 私有(private)成员(member)

但是,如果我们将派生类向上转型到它的父类,我们是否可以访问父类的私有(private)成员并且父类的 friend 现在可以申请这个向上转型的类吗?

我倾向于认为向上转换的派生类将无法访问父类的私有(private)方法和变量,因为派生类首先没有继承它们是有原因的。

(以下代码是验证答案验证后​​添加的)

这段c++代码用来测试我问的问题:

    #include <iostream>
class A;
void funcGetAVal(A);

class A
{
private:

int aVal;
friend void ::funcGetAVal(A);
public:
A()
{
aVal = 0;
}
};

class B : public A
{
public:
int bVal;
B() : A()
{
bVal = 0;
}
};

void funcGetAVal(A aClass)
{
std::cout << "A val accessed from friend function: " << aClass.aVal << std::endl;
}


int main()
{
B * b = new B;
A * a = new A;
A * bNowA = reinterpret_cast<A *>(b); //This reinterprets the instance of the derived class into an instance of the base class
//std::cout << bNowA->aVal << std::endl; //This caused a compile-time error since aVal is a private member of A
::funcGetAVal(*a); //This calls the funcGetAVal function with an instance of the base class
::funcGetAVal(*bNowA); //This calls the funcGetAVal function with an instance of the derived class reinterpreted as the base class
//Both funcGetAVal function calls print out 0
return 0;
}

结果与R Sahu的回答一致。从 B 的实例访问 A 的私有(private)成员导致错误,友元函数能够访问派生类的 aVal。

最佳答案

However if we upcasted the derived class to its parent class, would we have access to the private members of the parent class

没有。

private 类的成员在类的范围内是可访问的。类的成员函数可以访问其私有(private)成员。通过在不是基类成员函数的函数中将派生类指针向上转换为基类指针,您将无法访问基类的 private 成员。您只能访问其 public 成员。

and would the Parent class's friends now apply to this upcasted class?

如果将指向基类的指针传递给基类的友元,则友元函数可以访问privateprotected 基类的成员。

关于c++ - C++ 中的向上转型是否允许访问父级的私有(private)成员或 friend ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36050870/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com