gpt4 book ai didi

c++ - C++继承更改成员

转载 作者:行者123 更新时间:2023-12-02 10:13:07 28 4
gpt4 key购买 nike

当前正在学习更多c++,并且我有一个问题:为什么我必须使用函数来更改父类的成员,而不是仅在不使用函数的情况下进行更改?

class Shape{
private:
int a;
protected:
int b;
public:
int c;
};

class Rectangle: public Shape{
public:
c = 123;
void change_c(){c = 321;}
};

最佳答案

像声明c = 123;中一样,为变量分配值在变量声明或在函数内执行的分配之外是非法的。这意味着您不能在派生类的类范围内执行它:

class Rectangle: public Shape{
public:
c = 123; // <-- illegal
int d = 123; // <-- OK, in C++11 and later
Rectangle() { c = 321; } // <-- OK
void change_c(){ c = 321; } // <-- OK
}

关于c++ - C++继承更改成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62822778/

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