2016-11-30 80 views
-1

我该如何在头文件中实现睡眠和睡眠。这是我到目前为止所尝试的,并且不起作用。我还不是很精通C++。我知道可以通过注释掉HTML中的相似内容,并且每个浏览器都使用特定的代码。通过创建一个类来决定使用哪一个睡眠和互相使用休眠睡眠

这是我与实践样本:

help.cpp使用的#ifdef的#else #ENDIF得到它的窗口之间的工作

#include <iostream> 
#include "pause.h" 

using namespace std; 


int main() { 

pause p;  

cout << "Hello"; 

p.pause(5000) 

cout << " World"; 

} 

有人在另一个线程和建议LINUX/UNIX

pause.h

#ifdef _WIN32 
    #include <windows.h> 


class pause 
{ 
    public: 
     void pause(unsigned milliseconds) 
     { 
      Sleep(milliseconds); 
     } 
}; 

#else 
     #include <unistd.h> 

class pause 
{ 
    public: 
     void pause(unsigned milliseconds) 
     { 
      usleep(milliseconds * 1000); // takes microseconds 
     } 
}; 

#endif 

不知何故,我必须写错了类,因为运行我的.cpp文件它不能识别我尝试创建的类或对象。

错误

Running /home/ubuntu/workspace/help.cpp 
In file included from /home/ubuntu/workspace/help.cpp:2:0: 
/home/ubuntu/workspace/pause.h:20:41: error: return type specification for constructor invalid 
     void pause(unsigned milliseconds) 
             ^
/home/ubuntu/workspace/help.cpp: In function ‘int main()’: 
/home/ubuntu/workspace/help.cpp:9:7: error: expected ‘;’ before ‘p’ 
pause p;  
    ^
/home/ubuntu/workspace/help.cpp:13:1: error: ‘p’ was not declared in this scope 
p.pause(5000) 
^ 
/home/ubuntu/workspace/help.cpp:15:1: error: expected ‘;’ before ‘cout’ 
cout << " World"; 
^ 


Process exited with code: 1 
+0

忽略构造函数定义中的'void'返回类型。 –

+0

回复:“我将如何实现睡眠并在头文件中休眠” - 您不**执行它们;他们已经被执行了,你需要**调用**或**使用**。 –

回答

1

你不能有一个成员函数的名称相同的类。 pause是类名,因此编译器会将您的pause函数(pause::pause)作为构造函数。

您可以重新命名该类为Pause,然后p.pause将调用Pause::pause函数,该函数是有效的。

+0

为什么不通过调用构造函数暂停? –

+0

谢谢,我没有意识到我已经做到了。我想也许我的结构搞砸了。我不确定是否应该把所有的课程都做成一个班级或一个班级,如果一个班级或一个班级为了其他目的而做。看起来后者运行,但现在Hello在打印之前等待世界。 ¯\ _(ツ)_ /¯如果这不是一回事,那是另一回事。我想这是编程.... – AsylumOfMind

0

好吧,我现在不在Windows电脑附近,但看起来您误解了某些班级符号。 为什么你用参数实现了构造函数pause::pause,但是调用none?你为什么要调用一个不存在的成员函数pause::pause,更不用说它与class pause同名?你迷惑了他们。

让我简化情况来说明这一点并让你看到。 如果你要打印数量,设置一个类PrintNumber,通过

TEST.CPP:

#include <iostream> 
#include "print-num.h" 

int main(void) 
{ 
    PrintNumber pr; 
    pr.printMe(5000); 
} 

打印num.h:

#ifndef _PRINTNUM_ 
#define _PRINTNUM_ 

#include <iostream> 

class PrintNumber 
{ 
public: 
    explicit PrintNumber(){}; 
    ~PrintNumber(){}; 

    void printMe(unsigned num) { std::cout << num << "\n"; } 
}; 

#endif 

这将大大。

替换我的打印号码Sleep()并重试? 您可以使用构造函数Pause::Pause(void)和成员函数Pause::sleepNow(unsigned)或类似名称命名类Pause