从 c++ 中的类创建对象

Create an object from a class in c++

本文关键字:创建对象 c++      更新时间:2023-10-16

我刚开始用c ++编程,我不明白为什么Xcode说"变量类型'Rect'是一个抽象类"。你可以在这里找到我的一部分代码:提前感谢您的帮助,

main(){
   Rect  r1(10,5,"R1");
return 0;
}
class Rect : public Figure
{
public:
  Rect(int l, int h,std::string Label) : Figure(l), _h(h),_Label(Label) {};
  ~Rect(){};
  std:: vector<std::string> toString() const;
protected:
    int _h;
    int _l;
  std::string _Label;
};
class Figure
{
public:
  Figure(int l):_l(l){}
  virtual std::vector<std::string> toStrings() const =0;
  virtual ~Figure();
protected:
  int _l;
};

这是标准错误。这意味着没有为要为其创建对象的类实现某些纯虚拟方法。

在这种情况下,Rect 必须实现 std::vector<std::string> toStrings() const 。要修复它:

class Rect : public Figure
{
public:
  Rect(int l, int h,std::string Label) : Figure(l), _h(h),_Label(Label) {};
  ~Rect(){};
  std:: vector<std::string> toStrings() const override
  {
     return {};
  }
protected:
    int _h;
    int _l;
  std::string _Label;
};

自C++11以来,override关键字有助于发现此类错误。