类是否可以在其构造函数的参数中设置它从另一个类继承的变量的值
Is it possible for a class to set the value of a variable that it inherited from another class in the parameter of its constructor?
类A
包含受保护的int x
。类 B
扩展类A
。现在,类B
要做的是将x
的值设置为其自己的构造函数中的传递参数。当我尝试这样做时,我收到错误:
"x" 不是类 "B" 的非静态数据成员或基类。
#include <string>
#include <iostream>
class A {
protected:
int x;
public:
A()
{
}
};
class B : public A {
public:
B(int x)
: x(x)
{
}
};
int main()
{
}
您可以"设置"它,但不能初始化它,因为在初始化基类对象时它已经初始化了。您可以像这样"设置"它:
B(int x)
{
this->x = x; // assignment, not initialization
}
对于A
的一个构造函数来说,处理A::x
的初始化会更有意义:
A(int x) : x(x) {}
然后在B
中使用它:
using A::A; // allows B b{42};
相关文章:
- 一个变量的输入值也会保存到另一个变量中
- 将双精度变量设置为另一个变量的值
- c++问题:给一个变量赋值后,另一个变量发生了变化
- 我如何将一个变量与另一个变量进行比较,例如我想如果(var1 > var2 x 1),然后执行此 c++
- 将 int 转换为字符串,然后连接另一个变量以创建完整扩展名,然后将其转换为 const_char*
- 如何将行的第一个单词作为一个变量,将行的其余部分作为另一个变量进行归档/存储
- 打印一个变量将打印另一个变量的值(以 C++ 为单位)
- 如何将一个变量声明为另一个变量的值
- C BITSHIFT导致另一个变量引起问题
- C++字符串类如何将一个变量转换为另一个变量?
- 如何将字符串作为变量与另一个变量字符串进行比较
- C++循环变量按另一个变量递增
- C++ - 将一个变量分配给另一个变量和将变量分配给引用变量有什么区别?
- C 如何基于另一个变量和某些算术定义变量的值
- 我可以使用变量模板声明另一个变量模板
- 在C++中使用另一个变量作为数组索引限制
- 当类名存储在另一个变量中时,如何创建类的实例
- 如何在 switch 语句之后将变量添加到另一个变量
- 从另一个变量访问变量
- 如何使用另一个变量声明一个变量