我是c++的新程序员,我有一个任务是编写一个多态任务。程序中有一个toString模板,我不允许编辑。
我有一个<< operator in which I call an overloaded method with each class, the print itself for example cout << and it works correctly, but if I want to use the toString method for the same thing, it only works sometimes. You don't know where I'm doing wrong. I am attaching the entire program: https://godbolt.org/z/e8rrqTsEY
PS:我没有选择架构(我的意思是有一些断言等)所以添加方法和其他一些方法就是这样
class CWindow
{
public:
...
CWindow& add(const CWindow &x);
virtual unique_ptr<CWindow> createInstance() const;
unique_ptr<CWindow> &search(int id);
...
virtual void printData(ostream &os, bool last) const;
friend ostream& operator << (ostream &os, const CWindow &src);
protected:
static multimap<int,unique_ptr<CWindow>> m_Db;
..
};
unique_ptr<CWindow> CWindow::createInstance() const
{
return make_unique<CWindow>(*this);
}
CWindow &CWindow::add(const CWindow &x)
{
unique_ptr<CWindow> ptr = x.createInstance();
..
m_Db.emplace(ptr->m_Id, move(ptr));
return *this;
}
unique_ptr<CWindow>& CWindow::search(int id) {
auto it = m_Db.find(id);
if (it != m_Db.end())
return it->second;
static unique_ptr<CWindow> null_ptr = nullptr;
return null_ptr;
}
void CWindow::printData(ostream &os, bool last) const
{
os << "[" << m_Id << "] Window " << "\"" << m_Title << "\" " << "(" << m_AbsPos.m_X << "," << m_AbsPos.m_Y << "," << m_AbsPos.m_W << "," << m_AbsPos.m_H << ")" << "\n";
bool lastt = false;
size_t index = 0;
for(const auto &x : m_Db)
{
lastt = index++ == (m_Db.size() -1 );
x.second->printData(os, lastt);
}
}
ostream& operator << (ostream &os, const CWindow &src)
{
src.printData(os, false);
return os;
}
class CButton : public CWindow
{
public:
..
virtual unique_ptr<CWindow> createInstance() const;
virtual void printData(ostream &os, bool last) const override;
};
void CButton::printData(ostream &os, bool last) const
{
os << "+- [" << m_Id << "] Button " << "\"" << m_Title << "\" (" << m_AbsPos.m_X << "," << m_AbsPos.m_Y << "," << m_AbsPos.m_W << "," << m_AbsPos.m_H << ")" << "\n";
}
unique_ptr<CWindow> CButton::createInstance() const
{
return make_unique<CButton>(*this);
}
template <typename _T>
string toString ( const _T & x )
{
ostringstream oss;
oss << x;
return oss . str ();
}
int main()
{
cout << "work:" << endl;
cout << *a . search ( 20 );
cout << "work:" << endl;
cout << toString(a);
cout << "not work" << endl;
toString ( *b . search ( 20 ) );
其他类还有CInput、CLabel和CComboBox,但它们的工作原理与CButton基本相同,所以这里省略。提前感谢所有评论
C++ 使用 toString 模板和列表对象 - 多态性