C++ 使用C++;外部类中的公共变量,从嵌套的私有类中删除
我收到了一些使用嵌套类的代码,因此:C++ 使用C++;外部类中的公共变量,从嵌套的私有类中删除,c++,qt,class,C++,Qt,Class,我收到了一些使用嵌套类的代码,因此: class outer : public YetAnotherObject { public: outer(); ~outer(); std::string* z; private: static outer* s_pInstance; class inner : public QThread { public: inne
class outer : public YetAnotherObject
{
public:
outer();
~outer();
std::string* z;
private:
static outer* s_pInstance;
class inner : public QThread
{
public:
inner() : QThread() {}
~inner() {}
protected:
void run()
{
z = "Hello, world";
while (1) { ... whatever ... }
}
}innerObj; // <-- note edit is here
};
outer* outer::s_pInstance = 0;
outer* outer::instance(QObject* par)
{
if (s_pInstance == 0)
{
s_pInstance = new outer(par);
}
return s_pInstance;
}
类外部:公共YetAnotherObject
{
公众:
外部();
~outer();
std::string*z;
私人:
静态外部*s_p站姿;
类内部:公共QThread
{
公众:
内部():QThread(){}
~inner(){}
受保护的:
无效运行()
{
z=“你好,世界”;
而(1){……随便……}
}
}innerObj;//z=“”;
。我想不起传递自引用而不是自指针的任何方法
扩展问题,如何将“this”传递给innerObj?向内部类添加指针或对外部类的引用
class inner : public QThread
{
public:
inner(outer *o) : QThread(), o(o) { }
~inner() {}
protected:
void run()
{
o->z = "Hello, world";
while (1) { ... whatever ... }
}
private:
outer *o;
};
尽管您不能将文本(“Hello,world”)分配给指向std::string的指针
编辑:
如您所愿,在上述代码中更改了对指针的引用,尽管您始终可以使用*this
获得自引用
如果要实例化内部,可以这样做:
class outer : public YetAnotherObject
{
public:
outer() : innerObj(this) { ... }
~outer();
std::string* z;
private:
static outer* s_pInstance;
class inner : public QThread
{
...
}innerObj;
};
代码中有两个问题: 1) 您不应该使用std::string指针,因为它实际上不应该这样使用
2)嵌套类在C++中与它的外类无关,即使嵌套在它里面。如你所见,它与在java中没有嵌套的情况是一样的。例如,嵌套类中没有隐式实例,等等。 为了访问外部类中的字符串或任何变量,您需要有一个指向outter类的引用或指针,例如以下方式:
class outer : public YetAnotherObject
{
public:
outer();
~outer();
std::string z; // First modification
private:
static outer* s_pInstance;
class inner : public QThread
{
public:
inner(outer& o) : QThread(), outerRef(o) {} // Second modification
~inner() {}
outer& outerRef; // Third modification
protected:
void run()
{
z = "Hello, world";
while (1) { ... whatever ... }
}
};
};
outer* outer::s_pInstance = 0;
outer* outer::instance(QObject* par)
{
if (s_pInstance == 0)
{
s_pInstance = new outer(par);
}
return s_pInstance;
}
这是因为在外部类中
z=“”
不起作用为什么要使用字符串指针?为什么不简单地使用std::string z;
?查看应用于原始问题的注释和编辑。谢谢。@WesMiller我根据您的注释修改了我的答案。@LaszloPapp我深表歉意。我在这个holliday上比平时走得更远,没有检查这个问题发帖。是的,你的答案很好。我用std::string*替换了一个复杂得多的typedef/类,该类包含一个字符串指针。我想这样可以省去很多解释。我想了解更多。