指出class C { protected: int x; public: C(int a): x(a){} }; class D :public C { private: int y; public: D(int a):y(a){ } };的错误
时间: 2024-04-02 17:33:50 浏览: 21
这段代码中有一个错误:在 `D` 类的构造函数中没有调用 `C` 类的构造函数来初始化 `C` 类的成员变量 `x`。正确的代码应该是:
```
class C {
protected:
int x;
public:
C(int a): x(a) {}
};
class D : public C {
private:
int y;
public:
D(int a, int b) : C(a), y(b) {}
};
```
在 `D` 类的构造函数中通过调用 `C` 类的构造函数来初始化 `C` 类的成员变量 `x`。
相关问题
class Parent { int x; public: int a; int b; }; class Son: public Parent { public: int f () const { int c = a+b; return x; } };
这段代码存在一个问题:
在类Son中,成员函数f()试图访问基类Parent中的私有成员变量x,但是在派生类中是无法直接访问基类的私有成员的。
要修正这个问题,可以将基类Parent中的x成员变量改为protected访问权限,或者在基类中提供一个公有成员函数来获取x的值。例如:
```c++
class Parent {
protected:
int x;
public:
int a;
int b;
int getX() const { return x; }
};
class Son : public Parent {
public:
int f() const {
int c = a + b;
return x; // 可以通过protected访问权限或者公有成员函数getX()来访问基类中的x成员变量
}
};
```
这样,在派生类Son中就可以通过protected访问权限或者getX()公有成员函数来获取基类Parent中的x成员变量的值,而不需要直接访问基类中的私有成员变量。
class A { private: int x; protected: int y() { x = 1; } public: int z; }; class B :public A { public: void u() { cout << x; } }; int main() { B b; b.z = 1; b.u(); }代码错误的原因,并改正
代码错误的原因是在类B中无法访问类A中的私有成员x。另外,类A中的函数y()没有返回值,也需要进行修正。正确的代码如下:
```
class A {
private:
int x;
protected:
int y() {
x = 1;
return x;
}
public:
int z;
};
class B : public A {
public:
void u() {
cout << y();
}
};
int main() {
B b;
b.z = 1;
b.u();
}
```
在类B中,我们可以通过继承自类A的保护成员函数y()来访问类A中的私有成员x。同时,我们修正了函数y()的返回值,确保它返回了一个整数。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.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)