I have a problem with calling member method of object which is a member of some class. What I mean? I have class CPosition
:
cposition.h
#ifndef CPOSITION_H
#define CPOSITION_H
class CPosition
{
public:
CPosition(QString name, QString description);
QString toString();
private:
QString m_name;
QString m_description;
};
#endif // CPOSITION_H
cposition.cpp
#include <QString>
#include "cposition.h"
CPosition::CPosition(QString name, QString description)
: m_name(name), m_description(description)
{
}
QString toString()
{
QString test("Test - method called!");
return test;
}
And then I have a class CPerson
in which one of member is pointer to CPosition
object. In method CPerson::getPosition
I would like to call method CPosition::getPosition
only if pointer exist:
cperson.h
#ifndef CPERSON_H
#define CPERSON_H
class CPosition;
class CPerson
{
public:
CPerson(QString name);
QString getPosition();
private:
QString m_name;
CPosition * m_position;
CEmployer * m_employer;
};
#endif // CPERSON_H
cperson.cpp
#include <QTextStream>
#include <QString>
#include "cperson.h"
#include "cposition.h"
CPerson::CPerson(QString name) : m_name(name){}
QString CPerson::getPosition()
{
QString str;
QTextStream cout(&str);
if(m_position) //here check if pointer exist
{
cout << "Position: " << m_position->toString(); //<---- here is problem
}
else
cout << "Position doesn't exist!!!" << endl;
return str;
}
When I build this project I get an error:
C:\Qt\Projects\Tutorial\qt2\cperson.cpp:28: error: undefined reference to `CPosition::toString()'
I'm using QtCreator IDE. Does anyone can help me with this issue or explain why this isn't working ?
When you define your toString()
method with
QString toString()
{
//code
}
prototype in cposition.cpp
file, it's not a member of the CPosition
class. That's why when you try to call this method from m_position
pointer which is of type CPosition
, you get undefined reference error because you haven't implemented the toString()
method decalred in cposition.h
file.
Change the prototype of the toString()
method in cposition.cpp
file from
QString toString()
to
QString CPosition::toString()
{
//write code here
}
so that compiler knows that toString()
method implemented in cposition.cpp
file is the one declared in cposition.h
file.
Basically you are not giving an implementation to the toString
method. The correct way should be:
QString CPosition::toString()
{
QString test("Test - method called!");
return test;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.