【发布时间】:2019-01-15 02:22:16
【问题描述】:
这是我的问题的简化版本,我想使用来自 2 个子类的函数修改基类中的变量(我的原始代码中的二维向量),同时保留修改后的变量并显示它。
基本上我想修改基类中声明的变量,通过调用不同子类的同名函数,修改后的变量将与所有子类共享。对不起,我对多态性的理解不好,还在努力消化。
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。
【问题讨论】:
-
a、b和c都是独立的实例 -
尝试致电
Shape1->showValue(),Shape2->showValue()。 -
也许你想要
static int test[3];。它在所有实例之间共享test。 -
Shape1->showValue(), Shape2->showValue() 将显示除修改后的随机数,静态给出对'Shape::test'的未定义引用
-
我为您提供了提示,而不是解决方案,因为您的目标不清楚。如果你不理解它们并且不能很好地编写代码我建议你从stackoverflow.com/questions/388242/…开始
标签: c++ polymorphism