I am not really good in c++ so I really need your help. I am using a method inside an object and I would like to access other object members. How can I do that in a better way and not violating OOP?
This is my .h
class XSection
{
private:
char *m_sname;
XSection *m_snext;
};
class XIniFile
{
private:
char *m_iname;
XSection *m_isections;
XSection *addSection(const char *);
}
and I have something like this in .cpp
XSection *XIniFile::addSection(const char *d)
{
XSection *sn = (XSection *) malloc (sizeof(XSection *));
sn->m_sname = strdup(d);
return sn;
}
I am having an error of char* XSection::m_sname is private char *m_name;
How could I use it?
In general, this is considered bad practice because it violates the concept of encapsulation . In this case, it would be best to give XSection a constructor that sets it up with the desired parameters, and use new instead of malloc. For example:
The constructor definition:
XSection(char* name);
Implementation:
XSection(char* name) : m_iname(name) { }
Usage:
XSection* sn = new XSection(strdup(d));
But to answer the question directly: if you must, you could make XIniFile a friend class of XSection:
class XSection
{
friend class XIniFile;
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.