从抽象类传递函数
Passing a function from an abstract class
我试图将打印函数从抽象类"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只是实现。
相关文章:
- 如何处理从一个对象传递到另一个在C++中具有公共抽象类的对象的消息
- 有没有办法按值将纯抽象类的所有子类传递给 C++ 中的函数?
- 将自定义函数传递到基抽象类中以延迟执行
- C ++如何在原始抽象类中创建一个函数,该函数接受派生类的输入
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 将另一个类的对象传递到当前类C++的构造函数中(不是成员初始化)
- 从抽象类继承以创建另一个抽象类时,我应该重新声明所有虚函数吗?
- 如何将子类作为函数的参数传递给期望基类,然后将该对象传递到指向这些抽象类对象的指针向量中?
- 将函数作为类中的参数传递
- 抽象类和构造函数
- C++:传递指向函数中类的指针会导致数据复制?
- C++ 构造函数传递对基类对象的引用
- C++ 将一组对象传递给抽象类的成员函数
- 对抽象类的引用不能传递给线程函数?
- 如何将回调函数传递给 libusb 批量传递函数C++类
- 通过抽象类将参数传递给祖父母类的构造函数
- 在派生类中为抽象类函数传递附加参数
- 编译错误:在类构造函数中将抽象类作为参数传递
- 如何对引用传递的抽象类使用绑定
- 从抽象类传递函数