新数据成员的多态性

2024-04-08

我想编写一个可以使用多态性初始化和返回不同类的对象的函数。我还希望这些类具有可以通过虚拟函数调用的不同数据成员。我下面写的可能有用。你能检查一下我是否有一些未定义的行为吗?谢谢你!我担心的一件事是,当我最后调用“删除多点”时,它不会释放“CRectangle”特有的数据成员“scale”。如果我的代码不起作用,有没有办法让它工作?

class CPolygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
    virtual int area ()
      { return (0); }
  };

class CRectangle: public CPolygon {
  public:
    int scale;
    int area ()
      { return (width * height * scale ); }
  };

CPolygon *polytestinner()
{
    CPolygon *polypoint = 0;

    int consoleinput = 2;
    if (consoleinput>1)
    {
        CRectangle *rectpoint = new CRectangle();
        rectpoint->scale = 4;
        polypoint = rectpoint;
    }
    polypoint->set_values(3,4);
    return polypoint;
}

void polytest()
{
    CPolygon *polypoint = polytestinner();
    gstd::print<int>(polypoint->area());    
    delete polypoint;
}

int main()
{
    polytest();
    return 0;
}

谢谢你!


我觉得有必要指出 Andrei Alexandrescu 的对象工厂架构。它允许您的架构增长,而无需在每次创建具体类型时修改工厂。它基于“回调寄存器”,并且实际上在某些库中作为通用组件实现。代码如下。

实时代码示例 http://liveworkspace.org/code/3g7eSF%240

#include<map>
#include<iostream>
#include<stdexcept>

// your typical base class
class Shape {
 public:
  virtual void Draw() const = 0;
  // virtual destructor allows concrete types to implement their own
  // destrucion mechanisms
  virtual ~Shape() {} 
};

// this factory architecture was suggested by Andrei Alexandrescu in
// his book "Modern C++ Design" --- read it to get the full
// explanation (and a more generic implementation); this is just an
// example
class ShapeFactory {
 public:
  // this typedef allows to "name" arbitrary functions which take no
  // arguments and return a pointer to a Shape instance
  typedef Shape* (*CreateShapeCallback)();

  Shape* CreateShape(int ShapeId) {
    // try to find the callback corresponding to the given shape id;
    // if no shape id found, throw exception
    CallbackMap::const_iterator it = m_callbacks.find(ShapeId);
    if(it == m_callbacks.end()) {
      throw std::runtime_error("unknown shape id");
    } else {
      // create the instance using the creator callback
      return (it->second)();
    }    
  }

  bool RegisterShape(int ShapeId, CreateShapeCallback Creator) {
    // returns true if shape was registered; false if it had already
    // been registered
    return m_callbacks.insert(CallbackMap::value_type(ShapeId, Creator)).second;
  }

  bool UnRegisterShape(int ShapeId) {
    // returns true if shape was unregistered, false if it was not
    // registered in the first place
    return m_callbacks.erase(ShapeId) == 1;
  }

 private:
  // the typedef simplifies the implementation
  typedef std::map<int, CreateShapeCallback> CallbackMap;
  // the callbacks are stored in a map int->callback (see typedef
  // above)
  CallbackMap m_callbacks;
};


// create some concrete shapes... you would do this in other CPP files
class Line : public Shape {
 public:
  void Draw() const {
    std::cout<<"Drawing a line"<<std::endl;
  }
};

// another concrete shape...
class Circle : public Shape {
 public:
  void Draw() const {
    std::cout<<"Drawing a circle"<<std::endl;
  }
};
// ... other concrete shapes...

enum ShapeIds {LINE=1, CIRCLE, COUNT};
Shape* CreateLine() { return new Line; }
Shape* CreateCircle() { return new Circle; }


int main() {
  // suppose this is the "singleton" instance for the ShapeFactory
  // (this is an example! Singletons are not implemented like this!)  
  ShapeFactory *factory = new ShapeFactory;
  factory->RegisterShape(ShapeIds::LINE, CreateLine);
  factory->RegisterShape(ShapeIds::CIRCLE, CreateCircle);

  Shape* s1 = factory->CreateShape(ShapeIds::CIRCLE);
  Shape* s2 = factory->CreateShape(ShapeIds::LINE);
  s1->Draw();
  s2->Draw();
  // will throw an error
  try {
    Shape *s3 = factory->CreateShape(-1);
    s3->Draw();    
  } catch(const std::exception& e) {
    std::cout<<"caught exception: "<<e.what()<<std::endl;    
  }
  return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

新数据成员的多态性 的相关文章

  • 使用 CLion 进行 OpenCV Windows 设置

    我想在 Windows 上为 CLion IDE 设置 OpenCV 我尝试使用 OpenCV 3 1 和 2 4 得到相同的结果 我有 Windows 10 64 位 CLion 使用 cygwin 环境 到目前为止我做了什么 1 从Op
  • 将 new 与 decltype 一起使用

    T t T is an implementation detail t new T want to avoid naming T to allow for flexibility t new decltype t error cannot
  • 为什么 F# 的默认集合是排序的,而 C# 的不是?

    当从 C 世界迁移到 F 最惯用的可能 思维方式时 我发现了这个有趣的差异 在 C 的 OOP mutable 世界中 默认的集合集合似乎是HashSet https learn microsoft com en us dotnet api
  • 在路由mvc 4中添加公司名称

    我一直在尝试为 Facebook 等用户提供在 URL 中添加公司名称的选项 http localhost 50753 MyCompany Login 我尝试过不同的网址 但没有成功 routes MapRoute name Default
  • 在现代 C++ 中,临时生命周期延长何时有用?

    在 C 中 您可以将函数的返回值 返回值 而不是引用 绑定到 const 引用 并且代码仍然有效 因为该临时对象的生命周期将延长到作用域末尾 例如 std string get string return abc void f const
  • 从代码中,如何创建对存储在附加属性中的对象的属性的绑定?

    我们有一个继承的附加属性来存储一个对象 在可视化树的更下方 我们希望从代码绑定到该对象的属性 通常我们像这样构建绑定的路径部分 var someBinding new Binding Path new PropertyPath Attach
  • 在 C# 中调用 C++ 库 [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 我有很多用 C 编写的库 我想从 C 调用这些库 但是 我遇到了很多问题 我想知道是否有书籍或指南告诉我如何做到这一点 Dll导入 htt
  • 如何使用 SOAP 且不使用 WSE 在 .NET 中签署 Amazon Web 服务请求

    亚马逊产品广告 API 以前称为 Amazon Associates Web Service 或 Amazon AWS 实施了一项新规则 即自 2009 年 8 月 15 日起 向其发送的所有 Web 服务请求都必须经过签名 他们在其网站上
  • 在开关中使用“goto”?

    我看到了一个建议的编码标准 内容如下Never use goto unless in a switch statement fall through 我不跟 这个 例外 案例到底是什么样的 这证明了goto 此构造在 C 中是非法的 swi
  • 如何制作可启动程序?

    所以 这个问题可能看起来很奇怪 但假设我编译了 int main void int x 3 int y 4 int z x y 是否可以让CPU这样运行 如何 例如 这允许我写入监视器吗 如果我没记错的话 内存中有些地方可以写入要显示的内容
  • Kotlin 中扩展函数的多态性

    我有几个我无法控制的课程 我已经在几个常见的 属性 上创建了几个同名的扩展方法 名称相同的扩展函数始终返回相同的值类型 尽管针对每种类型的接收器以不同的方式计算 这里有一个简化的基于仅一个属性的内置类型的示例 DOES NOT COMPIL
  • 如何在三个 IEnumerable 上使用 Zip [重复]

    这个问题在这里已经有答案了 可能的重复 使用 Linq 从 3 个集合创建项目 https stackoverflow com questions 5284315 create items from 3 collections using
  • 使用具有抗锯齿功能的 C# 更改抗锯齿图像的背景颜色

    我有一个图像需要更改背景颜色 例如 将下面示例图像的背景更改为蓝色 然而 图像是抗锯齿的 所以我不能简单地用不同的颜色替换背景颜色 我尝试过的一种方法是创建第二个图像 仅作为背景 并更改其颜色并将两个图像合并为一个图像 但是这不起作用 因为
  • 引用/指针失效到底是什么?

    我找不到任何定义指针 引用无效在标准中 我问这个问题是因为我刚刚发现 C 11 禁止字符串的写时复制 COW 据我了解 如果应用了 COW 那么p仍然是一个有效的指针并且r以下命令后的有效参考 std string s abc std st
  • ASP.NET MVC 路由:如何从 URL 中省略“索引”

    我有一个名为 StuffController 的控制器 具有无参数索引操作 我希望从表单中的 URL 调用此操作mysite com stuff 我的控制器定义为 public class StuffController BaseContr
  • .NET 4 的条件编译[重复]

    这个问题在这里已经有答案了 可能的重复 条件编译和框架目标 https stackoverflow com questions 2923210 c sharp conditional compilation and framework ta
  • 选择查询不适用于使用Parameters.AddWithValue 的参数

    C 中的以下查询不起作用 但我看不出问题所在 string Getquery select from user tbl where emp id emp id and birthdate birthdate cmdR Parameters
  • 在 C#.NET 中安全删除文件

    在我正在做的一个项目中 我想为用户提供 安全 删除文件的选项 例如 用随机位或 0 覆盖它 在 C NET 中是否有一种简单的方法可以做到这一点 效果如何 你可以调用系统内部删除 http technet microsoft com en
  • 如何调试 .NET 运行时中的内部错误?

    我正在尝试调试一些处理大文件的工作 代码本身works 但 NET 运行时本身会报告零星错误 对于上下文 这里的处理是一个 1 5GB 文件 仅加载到内存中一次 在循环中处理和释放 故意尝试重现此否则不可预测的错误 我的测试片段基本上是 t
  • C++ 中 void(*)() 和 void(&)() 之间的区别[重复]

    这个问题在这里已经有答案了 在此示例代码中 func1是类型void int double and funky是类型void int double include

随机推荐