【发布时间】:2014-04-12 05:31:33
【问题描述】:
我正在尝试将打印函数从抽象类“shape”传递给派生类“circle”和“square”。它应该打印出“名称:”,然后是形状的名称。由于某种原因,它无法正常工作。我需要为每个派生类重新声明和重新定义打印吗?还是我没有正确传递它,或者名称没有正确存储在派生函数中?
为了澄清:我只想让它在遍历数组时正确打印出名称。任何建议将不胜感激。
谢谢!
这些应该是相关的代码:
print() 在 shape 头文件中声明。
In shape.cpp
void shape::setName( const string &shapeName )
{
name = shapeName;
}
//return name
string shape::getName() const
{
return name;
}
void shape::print() const
{
cout<<"Name: "<<getName()<<endl;
}
方形构造函数://(与其他派生类相同)
square::square(const string &name, const int &sideLength)
: shape ( name )
{
setSideLength(sideLength);
}
主要是:
//create derived class objects with side lengths:
square square1(
"square", 3);
//an object array named shapesArray is created with an instance of square and circle
for(int x = 0; x < 3; x++)
{
shapesArray[x]->print();
cout<<"The distance around this shape is: "<<shapesArray[x]->getDistanceAround()<<endl;
【问题讨论】:
-
通过打印功能?你的意思是超载吗?您是否将其设为虚拟(看起来您是从指针调用)?
-
我想我正在尝试通过它。有人告诉我使用指向它的指针而不是执行 print()。我认为 print 函数将包含在派生类和原始函数中,但它不会打印出它们的名称。
-
您的
shape类或square类中是否定义了print()? -
你能发布
print的实现吗? -
@R Sahu 我唯一使用或引用它的地方是我在这里复制的代码中。我应该在他们的 cpp 文件中为每个派生类都有一个特定的实现吗?
标签: c++ polymorphism abstract-class derived-class