错误:未在此范围内声明'小时'

use*_*491 0 c++ class cmake

我用c ++编写了一个代码.我试着在Kdevelop中使用CMake.

我的头文件Newtime.h

class NewTime
{
public:
  NewTime(int = 0, int = 0, int = 0);    //constructor
  void setTime(int, int, int);    // set time
  void dispTime();    //print time
private:
  int hour;
  int minute;
  int second;
};
Run Code Online (Sandbox Code Playgroud)

对于NewTime.cpp,我在下面写道:

#include <iostream>
#include <stdio.h>
#include "NewTime.h"
//
NewTime::NewTime(int hr, int min, int sec)  
{
  setTime(hr, min, sec);
}
//
void NewTime::setTime(int h, int m, int s)
{
  hour = ((h >= 0 && h < 24) ? h : 0);
  minute = ((m >= 0 && m < 60) ? m : 0);
  second = ((s >= 0 && s < 60) ? s : 0);
}
//***
void Newtime::dispTime()
{
  std::cout << ((hour == 0 || hour == 12) ? 12 : hour % 12)
       << " : " << (minute < 10 ? "0" : "") << minute
       << " : " << (second < 10 ? "0" : "") << second
       << (hour < 12 ? " AM" : " PM") << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

而对于主体是:

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

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

int main()
{
  NewTime t1, //use default arguments
          t2(2), //only hour defined
          t3(21, 34), //second as default
          t4(12, 25, 42), //everything is defined
          t5(53, 343, 234); //invalid hour
  std::cout << "constructed with: " << std::endl;
  std::cout << "use default arguments: " << std::endl;
  t1.dispTime();
  std::cout << "only hour: " << std::endl;
  t2.dispTime();
  std::cout << "hour and minute: " << std::endl;
  t3.dispTime();
  std::cout << "all defined: " << std::endl;
  t4.dispTime();
  std::cout << "invalid values: " << std::endl;
  t5.dispTime();
  std::cin.get();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

但我得到了这个错误:

compiling NewTime.cpp (c++)
/home/hasadi/Desktop/tmp/C++/4-6-class-newtimer/newtimer/NewTime.cpp:17: error: ‘Newtime’ has not been declared
/home/hasadi/Desktop/tmp/C++/4-6-class-newtimer/newtimer/NewTime.cpp: In function ‘void dispTime()’:
/home/hasadi/Desktop/tmp/C++/4-6-class-newtimer/newtimer/NewTime.cpp:19: error: ‘hour’ was not declared in this scope
/home/hasadi/Desktop/tmp/C++/4-6-class-newtimer/newtimer/NewTime.cpp:20: error: ‘minute’ was not declared in this scope
/home/hasadi/Desktop/tmp/C++/4-6-class-newtimer/newtimer/NewTime.cpp:21: error: ‘second’ was not declared in this scope
Run Code Online (Sandbox Code Playgroud)

任何的想法?我很困惑..

提前谢谢你的帮助

Jon*_*fer 5

你有一个拼写错误,编译器抛出的第一个错误告诉你:

[…]/NewTime.cpp:17: error: ‘Newtime’ has not been declared
Run Code Online (Sandbox Code Playgroud)

您必须Newtime将dispTime实现更改为NewTime并且它将构建.现在,编译器不知道dispTime实现与NewTime-class 相关联.

通常,如果你进入'varname' was not declared in this scope内部方法实现,它通常是缺失或拼写错误或类错误的类/结构类型名称.

正如John Zwinck在评论中所建议的那样,第一个错误通常是最相关的.您可能只需查看第一个错误就可以自己解决问题.