C++ 子类怎么调用父类的成员对象
时间: 2023-09-05 12:13:54 浏览: 71
在 C++ 中,子类可以通过父类的构造函数或者父类的成员函数来调用父类的成员对象。具体来说,有以下两种方法:
1. 在子类的构造函数中调用父类的构造函数:
```c++
class Parent {
public:
Parent(int x): num(x) {}
protected:
int num;
};
class Child : public Parent {
public:
Child(int x, int y): Parent(x), val(y) {}
private:
int val;
};
```
在上面的代码中,子类 Child 的构造函数中通过 Parent(x) 调用了父类 Parent 的构造函数,从而初始化了父类的成员变量 num。
2. 在子类的成员函数中通过父类的指针或引用调用父类的成员对象:
```c++
class Parent {
public:
Parent(int x): num(x) {}
int getNum() { return num; }
protected:
int num;
};
class Child : public Parent {
public:
Child(int x, int y): Parent(x), val(y) {}
int getParentNum() { return Parent::getNum(); }
private:
int val;
};
```
在上面的代码中,子类 Child 的成员函数 getParentNum() 中通过 Parent::getNum() 调用了父类 Parent 的成员函数 getNum(),从而获取了父类的成员变量 num 的值。注意,在成员函数中调用父类的成员函数时要使用作用域解析运算符 ::。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)