PDA

View Full Version : Using toString() of another class



quty
28th August 2015, 12:04
Hi,

Ive got 2 classes and I would like Class2 to use the toString() of Class1, but Im getting the following error:

error: cannot call member function 'QString Process::toString() const' without object
.arg(Process::toString());
^
Class1:
QString Process::toString() const
{
return QString("Type: %1, Date: %2, Number: %3, Price: %4")
.arg(m_Type).arg(m_Date.toString("dd.MM.yyyy")).arg(m_NoOfItems).arg(m_PricePerItem);
}

Class2:
QString Items::toString() const
{
QString product = QString("Item process: %1\n")
.arg(Process::toString());

return process;
}

Please assist.

ars
28th August 2015, 12:19
Hello,

the error message you get is pretty clear: you need to call method toString() with an object of type Process. Your way of calling toString() can only be used if toString() is a static member function of class Process. So your code of class 2 should look like


QString Items::toString(const Process& process) const
{
QString product = QString("Item process: %1\n")
.arg(process.toString());

return product;
}

Note that we pass a reference to a Process object to the Items::toString() method and we use this reference for accessing the Process object toString() method.

One more note: your code would also fail compiling at line

return process;

Best regards
ars

P.s.: please use code tags in your post.