2011-03-08 56 views
0

我有两个类一和二。两者都运行线程。第二类是对第一类声明的函数进行线程化。这是通过在第二类的run方法中调用它来完成的。我试图调用/启动线程两个在一个的构造函数中,以便这两个线程一起运行。 我得到范围错误。因为缺少语法。代码如下给出C++在第一类的构造函数中创建第二类对象 - 多线程

#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); 

} 

代码旁边注释中给出的错误是。

error: 'Two' was not declared in this scope

error: expected ';' before 'b'

error: 'b' was not declared in this scope

我缺少什么语法?

+0

解决方案的实际点是由Erik提供的http://stackoverflow.com/questions/5230444/c-qthread-同时启动2线程 – 2011-03-08 12:40:14

回答

1

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

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

+0

这似乎消除了构建错误。 – 2011-03-08 08:08:25

+0

你有没有尝试将它们分成不同的源文件? – YeenFei 2011-03-22 00:57:04

+0

是的,这删除了构建错误,这个问题的工作是[this](http://stackoverflow.com/questions/5230444/c-qthread-starting-2-threads-并发) – 2011-03-22 04:46:13

1

嗯......我可能会错过一些东西,但是好像你的问题是One的定义甚至没有看到两个声明;将声明移动到头文件中,例如

class 1:public QThread { public: One(); void run(); void beep(); };

然后在.cpp: One :: One() { Two b; b.start(); b.wait(); };

与Two相似。 这将使它建立;我不会对此进行评论,因为我不是很熟悉QT

相关问题