gpt4 book ai didi

c++ - 如何实现包含不同类型单元格的表格?

转载 作者:搜寻专家 更新时间:2023-10-31 02:22:13 24 4
gpt4 key购买 nike

这是我正在尝试做的事情:我想制作一个二维单元阵列。每个单元格可以包含一个数字或一个字符串。然后我想将该表传递给我制作的表达式解析器。我需要解析器能够识别表达式中的单元格是否包含一个数字 - 这很好 - 或一个字符串 - 不好。

我是这样尝试的:我创建了一个抽象基类 CCell 和三个派生类。派生的一种是CCellEmpty,一种是CCellText,最后一种是CCellNumber

该表是指向基类的二维指针数组。在表达式解析器中,我需要从 Number 类中获取数字。问题是您不能通过基类指针访问派生类的私有(private)成员。嗯,在基类中我可以为数字创建一个虚拟的 getter。在数字类中,它将返回所需的数字,但我还需要为 Text 类和 Empty 类实现它。对于他们两个,它都会抛出异常。
注意:我知道可以使用 dynamic_cast 来完成,但我不想那样做。

这样做好吗?我是 C++、面向对象编程和多态性的新手,所以如果有更好的设计方法,我会很高兴听到。我想以正确的方式去做,而不仅仅是这样它会以某种方式起作用。

这是我现在使用的代码:

#include <string>

class NotTextException{};
class NotNumberException{};

class CCell
{
public:
virtual ~CCell ( void ){}
virtual int GetNumber ( void ) const = 0;
virtual std::string GetText ( void ) const = 0;
};

class CCellEmpty : public CCell
{
public:
virtual int GetNumber ( void ) const {
throw NotNumberException();
}
virtual std::string GetText ( void ) const {
throw NotTextException();
}

};

class CCellText : public CCell
{
public:
CCellText ( const std::string & text )
: m_text(text)
{}
virtual int GetNumber ( void ) const {
throw NotNumberException();
}
virtual std::string GetText ( void ) const {
return m_text;
}

private:
std::string m_text;
};

class CCellNumber : public CCell
{
public:
CCellNumber ( const int num );
virtual int GetNumber ( void ) const {
return m_number;
}
virtual std::string GetText ( void ) const {
throw NotTextException();
}

private:
int m_number;
};

最佳答案

电芯和电路板

Is this a good way to do it? I am new to C++, object oriented programming and polymorphism, so if there is a better way to design it I will be glad to hear it.

是的,有一个更好的方法:您可以使用 boost::variant 来表示一个单元格对象,并结合 boost::optional 将访问者应用于每个单元格> 表示不存在单元格对象。

您的电池和电路板类型如下所示:

using cell = boost::variant<int, std::string>;
using board = std::array<boost::optional<cell>, 100>;

在 2 行代码中你就完成了。此时,您只需编写一个通用访问器,它会尝试获取 Element 类型的元素,否则会抛出 Except 类型的异常:

template<typename Type, typename Except>
struct element_getter : boost::static_visitor<Type> {
template<typename Other>
Type operator()(Other const&) const { throw Except(); }

Type operator()(Type const& x) const { return x; }
};

用法

此时,您只需使用 boost::apply_visitor 将访问者应用到每个单元格,具体取决于单元格是否包含元素。

一个用法示例是:

board b;
b[45] = 42;
b[78] = 108;
auto sum = std::accumulate(begin(b), end(b), 0,
[](int counter, boost::optional<cell> cell) {
return counter +
boost::apply_visitor(
element_getter<int, not_number_error>(),
cell.get_value_or(0)
);
}
);

此代码将计算所有包含数字的单元格,但如果单元格包含字符串则抛出异常。

Live demo

关于c++ - 如何实现包含不同类型单元格的表格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30544583/

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