【问题标题】:c++ creating object of second class in the constructor of first class - multithreadingc ++在第一类的构造函数中创建第二类的对象 - 多线程
【发布时间】:2011-03-08 07:45:50
【问题描述】:

我有两个班级一和二。两者都运行线程。第二类是线程化在第一类中声明的函数。这是通过在第二个类的 run 方法中调用它来完成的。我试图在一个的构造函数中调用/启动线程二,以便这两个线程一起运行。 我得到范围错误。由于缺少语法。代码如下

#include <QtGui>
#include<iostream>
using namespace std;
class One:public QThread
{
public:
    One()
    {
        Two b; // error: 'Two' was not declared in this scope error: expected ';' before 'b'
        b.start();//error: 'b' was not declared in this scope|
        b.wait();
    };
    void run();
    void beep();
};
void One::run()
{

}
void One::beep()
{

}
class Two:public QThread
{
public:
    Two()
    {

    };
    void run();
};
void Two::run()
{
    One a;
    a.beep();
}
int main(int argc,char* argv[])
{
    One a;
    a.start();
    a.wait();
    return(0);

}

代码旁边的 cmets 中给出的错误是 .

错误:“二”未在此声明 范围

错误:预期为 ';'在'b'之前

错误:“b”未在此声明 范围

我缺少什么语法?

【问题讨论】:

标签: c++ multithreading class constructor qthread


【解决方案1】:

您的错误是由编译器试图实例化尚未声明的类/类型引起的。

您应该将声明和实现拆分为单独的文件,最好是广泛使用的 .h 和 .cpp 格式。然后将类型的标头包含在您需要的 cpp 中。

【讨论】:

  • 是的,消除了构建错误,解决这个问题的方法是this
【解决方案2】:

嗯...我可能遗漏了一些东西,但您的问题似乎是 One 的定义甚至没有看到两个的声明;将声明移动到头文件中,例如

第一类:public QThread { 上市: 一(); 无效运行(); 无效哔(); };

然后在 .cpp 中: 一一() { 二乙; b.开始(); b.等待(); };

与二类似。 这将使它构建;我一般不会评论它,因为我对 QT 不是很熟悉

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    相关资源
    最近更新 更多