这是我问题的简化版本,我想使用两个子类中的函数来修改基类中的变量(原始代码中的2d向量),同时保留修改后的变量并显示它。
基本上,我想通过从不同的子类中调用具有相同名称的函数来修改基类中声明的变量,并且修改后的变量将与所有子类共享。很抱歉,我对多态性的理解不清,仍在尝试中进行总结。
PS:我从下面删除了构造函数和虚拟析构函数,因为stackoverflow不允许我这样做。
#include <iostream>
using namespace std;
class Shape
{
protected:
int test[3];
public:
virtual void chgValue() {}
void setInitialValue();
void showValue();
};
void Shape::setInitialValue() //sets test to {1,2,3}
{
test[0]=1;
test[1]=2;
test[2]=3;
}
void Shape::showValue() //display elements of test
{
for(int i=0;i<3;i++)
cout<<test[i]<<" ";
}
class Square : public Shape //child class 1
{
public:
void chgValue()
{
test[1]=5;
}
};
class Triangle : public Shape //child class 2
{
public:
void chgValue()
{
test[2]=7;
}
};
int main()
{
Shape a;
Square b;
Triangle c;
Shape *Shape1=&b;
Shape *Shape2=&c;
a.setInitialValue(); //sets test to {1,2,3}
Shape1->chgValue(); //change test[1] to 5
Shape2->chgValue(); //change test[2] to 7
a.showValue(); //shows 1 2 3 instead of 1 5 7
return 0;
}
预期输出为1 5 7,但实际输出为1 2 3。
答案 0 :(得分:2)
我想您在这里对OOP的概念有误解:
Shape a;
Square b;
Triangle c;
这意味着您已经定义了三个不同的对象,它们在RAM中占据了三个独立的内存区域。
a.setInitialValue();
这只是设置int test[3];
对象的a
的元素。
Shape *Shape1=&b;
Shape *Shape2=&c;
Shape1->chgValue();
Shape2->chgValue();
这应分别更改int test[3];
和b
对象中c
的元素;但这不会影响a
对象。
毕竟,{p}的int test[3];
元素:
a
:1 2 3 b
:x 5 x c
:x x 7 注意:x在这里表示不确定(可能会在RAM中留下一些垃圾)。
已更新以处理OP的评论
如果您真的要“通过在不同的子类中调用具有相同名称的函数来修改基类中声明的变量,并且修改后的变量将与所有子类共享”,则您可以在int test[3];
中声明Shape
为静态,如下所示:
class Shape
{
protected:
static int test[3];
public:
// other code goes here
// ...
};
int Shape::test[3];
// other code goes here
// ...