使用父类构造函数为继承的变量重新赋值
Using parent class constructor to reassign value to inherited variables
我有一个继承自类a的c++类B。我可能错过了OOP的一个重要概念,这当然是相当琐碎的,但我不明白如何在B的实例化之后,在B内部使用a的构造函数将新值仅重新赋值给从a继承的局部变量:
A
class A{
public:
A(int a, int b){
m_foo = a;
m_bar = b;
}
protected:
int m_foo;
int m_bar;
};
B类
class B : public A{
public:
B(int a, int b, int c):A(a,b),m_loc(c){};
void resetParent(){
/* Can I use the constructor of A to change m_foo and
* m_bar without explicitly reassigning value? */
A(10,30); // Obviously, this does not work :)
std::cout<<m_foo<<"; "<<m_bar<<std::endl;
}
private:
int m_loc;
};
主要int main(){
B b(0,1,3);
b.resetParent();
return 1;
}
在这个具体的例子中,我想调用b.resetParent()
,它应该调用A::A()
来将m_foo
和m_bar
(在b
中)的值分别更改为10和30。因此,我应该打印"10;30"而不是"0;1"。
非常感谢您的帮助,
不能使用构造函数来更改对象,只能使用构造函数来创建对象。要改变一个已经构造的对象,你需要使用它的public
和protected
(如果是派生的class
)成员。在您的示例中,A
需要实现reset()
成员函数,该函数可用于稍后重置其状态。
不能,不能调用基类构造函数来重置值。但是,您想要重置的值被声明为protected
,这意味着B
可以直接访问它们:
void resetParent()
{
m_foo = 10;
m_bar = 30;
std::cout << m_foo << "; " << m_bar << std::endl;
}
如果 A
定义了=
赋值操作符,您可以声明一个临时A
实例并将其赋值给基类:
void resetParent()
{
*this = A(10, 30);
// or:
// A::operator=(A(10, 30));
std::cout << m_foo << "; " << m_bar << std::endl;
}
相关文章:
- 在C++中,将int值赋给enum,反之亦然
- C++:将值赋值给原始数据类型(例如布尔值)是原子操作吗?
- C++双重枚举值赋值
- 如何重载 const 对象的 [],以便值赋值不会导致编译错误
- std::vector 不支持右值赋值
- std::memcpy或显式字符值赋值-在C++中等于合法
- C++字符数组值赋值
- 在同一步骤中构造新对象和赋值
- 左值和右值赋值错误
- 将真值赋给浮点值
- 在 C++ 中通过引用返回 - 引用赋值与值赋值
- C++ 将静态 int 的值赋值分配给 int
- 提升::任何赋值字符串值
- C/C++ 值赋值到 std::queue<char*>
- 将int值赋给指针
- C++11:为什么允许赋值右值
- 将值赋给常量的语法或语义错误
- 无法将值赋给双精度类型
- 用于具有const数据成员的类的move和右值赋值操作符
- 新的表达式求值顺序(指针赋值)