gpt4 book ai didi

C++——继承

转载 作者:行者123 更新时间:2023-12-04 01:07:56 28 4
gpt4 key购买 nike

我原以为下面的代码片段会产生编译错误,因为派生类不会有我试图在 pub_fun() 中访问的 priv_var。但是它编译了,我得到了下面提到的输出。有人可以解释这背后的理论吗?

class base {

private:
int priv_var = 90;

public:
int pub_fun();

} b;

class derived : public base {
} d;

int base::pub_fun() { cout << priv_var << "\n"; }

int main() {
d.pub_fun();
return 0;
}

输出:

90

最佳答案

它编译因为方法 pub_fun 是在基类中声明的。这就是它可以访问私有(private)成员 priv_var 的原因。如果您在 derived 中创建了一个方法并试图访问 priv_var,您将会看到编译时错误。

关于C++——继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65714413/

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