gpt4 book ai didi

带有访问修饰符的 C++ 继承

转载 作者:行者123 更新时间:2023-11-30 00:38:39 27 4
gpt4 key购买 nike

我有这段代码

    #include <iostream>
using namespace std;
class Polygon
{
public:
int publicmemberPolygon;
private:
int privatememberPolygon;
protected:
int protectedmemberPolygon;
};

class Square : public Polygon
{
public:
int Getter();
};
int Square::Getter()
{
return privatememberPolygon;
}

int main()
{
}

问题是,为什么 privatememberPolygon 无法访问?是不是,当你有一个派生类时,它的所有成员/函数都被复制了?谢谢

最佳答案

不,当您从基类公开派生时,派生类只能访问其 publicprotected 成员。您还可以阅读此 FAQ .

看这个例子:

class Base
{

public:
void setPrivate(int p)
{
m_private = p;
}

public:
int m_public;
protected:
int m_protected;
private:
int m_private;
};

class Derived : public Base
{
public:
void f()
{
m_public = 0; // Can access public member of base class
m_protected = 0; //Can access protected member of base class
m_private = 0; //Compiler error- Can not access private member of base class
}
};

int main() {

Derived d;
d.setPrivate(10); //m_private is still part of the derived class. Hence can call setPrivate
return 0;

}

关于带有访问修饰符的 C++ 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10264873/

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