从抽象类传递函数

Passing a function from an abstract class

本文关键字:传递函数 抽象类      更新时间:2023-10-16

我试图将打印函数从抽象类"shape"传递到派生类"circle"answers"square"。它应该打印出"Name:",后面跟着形状的名称。出于某种原因,它不能正常工作。我需要为每个派生类重新声明和重新定义print吗?或者我没有正确传递它,或者名称没有正确存储在派生函数中?

澄清一下:我只是想让它在循环遍历数组时正确地打印出名称。如有任何建议,不胜感激。

谢谢!

这些应该是相关的代码:

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);
}

main:

//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;

我认为你想做的是如下所示。请注意,您需要通过专门调用setname方法或在派生类的构造函数中正确设置"name"。

  class Shape
  {
   public:
   string name; 
   void setName( const string &shapeName )
   {
     name = shapeName;
    }
   string getName() const
  {
   return name;
   }
   void print() const
  {
   cout<<"Name: "<<getName()<<endl;
   }
  };
  class Circle:public Shape
  {
   public:
    Circle()
    {
      name = "Circle";
    } 
   };
   class Square:public Shape
   { 
    public:
    Square()
    {
      name = "Square";
    }
    };
  int main()
  {
   Shape* shapesArray[5];
   shapesArray[0]->setName("check");
   Circle lCircle;      
   shapesArray[1]=&lCircle;
   Square lSquare;
shapesArray[2]=&lSquare;  
   for(int x = 0; x < 3; x++)
   {
     shapesArray[x]->print();
  }

}

如果你打算使用指针,最好使用c++的动态绑定特性和virtual函数:

virtual string shape::getName() const //in shape
{
    return "shape";
}
virtual string square::getname() const //in square
{
    return "square";
}
shape *s();
s = &shapeobj;
s.getName(); //shape
s = &squareobj;
s.getName(); //square

从你的标题,我假设你有一个抽象基类形状在头shape.h,你还没有给我们看,其中声明打印()。

在每个派生类中算作声明。现在您需要在每个派生类中定义 print(),以提供实现。它看起来像:

void square::print() {
  // implementation
}
void triangle::print() {
  // implementation
}
无论您在cpp文件中提供定义,您还需要在头文件中提供声明。头文件是类的声明,cpp只是实现。