gpt4 book ai didi

c++ - 测试 C++ 类的特性

转载 作者:太空宇宙 更新时间:2023-11-04 15:10:12 25 4
gpt4 key购买 nike

我有一组类描述了一组逻辑框,这些框可以容纳东西并对其进行操作。我有

struct IBox // all boxes do these
{
....
}

struct IBoxCanDoX // the power to do X
{
void x();
}

struct IBoxCanDoY // the power to do Y
{
void y();
}

我想知道对于这些类的客户来说,处理这些可选功能的“最佳”或“最喜欢”的习惯用法是什么

一)

    if(typeid(box) == typeid(IBoxCanDoX))
{
IBoxCanDoX *ix = static_cast<IBoxCanDoX*>(box);
ix->x();
}

二)

   IBoxCanDoX *ix = dynamic_cast<IBoxCanDoX*>(box);
if(ix)
{
ix->x();
}

c)

if(box->canDoX())
{
IBoxCanDoX *ix = static_cast<IBoxCanDoX*>(box);
ix->x();
}

d) 现在不同的类结构

struct IBox
{
void x();
void y();
}
...
box->x(); /// ignored by implementations that dont do x

e) 除了

相同
box->x() // 'not implemented' exception thrown

f) 显式测试函数

if(box->canDoX())
{
box->x();
}

我相信还有其他人。

编辑:

只是为了让用例更清晰

我通过交互式用户界面向最终用户公开这些内容。他们可以输入“make box do X”。我需要知道 box 是否可以做 x。或者我需要禁用“使当前框执行 X”命令

EDIT2:感谢所有回答者

正如 Noah Roberts 指出的那样 (a) 不起作用(解释了我的一些问题!)。我最终做了 (b) 和一个轻微的变体

   template<class T>
T* GetCurrentBox()
{
if (!current_box)
throw "current box not set";
T* ret = dynamic_cast<T*>(current_box);
if(!ret)
throw "current box doesnt support requested operation";
return ret;
}
...
IBoxCanDoX *ix = GetCurrentBox<IBoxCanDoX>();
ix->x();

并让 UI 管道很好地处理异常(我并不是真的在抛出裸字符串)。

我也打算探索Visitor

最佳答案

我建议在 C++ 中使用访问者模式来解决像这样的双重调度问题:

class IVisitor
{
public:
virtual void Visit(IBoxCanDoX *pBox) = 0;
virtual void Visit(IBoxCanDoY *pBox) = 0;
virtual void Visit(IBox* pBox) = 0;
};

class IBox // all boxes do these
{
public:
virtual void Accept(IVisitor *pVisitor)
{
pVisitor->Visit(this);
}
};

class BoxCanDoY : public IBox
{
public:
virtual void Accept(IVisitor *pVisitor)
{
pVisitor->Visit(this);
}
};
class TestVisitor : public IVisitor
{
public:
// override visit methods to do tests for each type.
};

void Main()
{
BoxCanDoY y;
TestVisitor v;
y.Accept(&v);
}

关于c++ - 测试 C++ 类的特性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3336859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com