0

我用 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;
};

对于 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;
}

主体是:

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

但我得到了这个错误:

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

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

提前谢谢你的帮助

4

2 回答 2

5

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

[…]/NewTime.cpp:17: error: ‘Newtime’ has not been declared

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

通常,如果您'varname' was not declared in this scope进入方法实现,通常是缺少或拼写错误或错误的类/结构类型名称。

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

于 2013-02-20T13:50:25.807 回答
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;
}

你用小写的 T 拼写它!

于 2013-02-20T13:52:17.830 回答