所以我的错误是错误1错误LNK2019:未解析的外部符号" class std :: basic_ostream> &安培; __cdecl运算符<<(class std :: basic_ostream>&,class Time const&)"函数_main c:\ Users \ marklaptop \ documents \ visual studio 2013 \ Projects中引用了(?? 6 @ YAAAV?$ basic_ostream @ DU?$ char_traits @ D @ std @@@ std @@ AAV01 @ ABVTime @@@ Z) \ ConsoleApplication6 \ ConsoleApplication6 \ main.obj ConsoleApplication6
这令人困惑,因为在我学校的计算机实验室一切正常,我没有收到此错误。我保存了文本并在家中打开了,因为链接错误而无法正常工作
#include <iostream>
#include "time.h"
using namespace std;
int main()
{
Time t1, t2, t3(123456), t4(-5);
cout << "t1 = " << t1 << '\n';
cout << "t2 = " << t2 << '\n';
cout << "t3 = " << t3 << '\n';
cout << "t4 = " << t4 << '\n';
return 0;
}
现在是我的头文件 #ifndef TIME_H #define TIME_H
#include <iostream>
using namespace std;
class Time {
public:
// constructors
Time(); //default constructor
Time(int s); // conversion constructor
Time(int d, int h, int m, int s); // days, hours, minutes,
friend ostream& operator<<(ostream& out, const Time& t);
private:
//member variables
int day;
int hour;
int minute;
int second;
};
#endif
最后是time.cpp文件
#include <iostream>
#include "time.h"
using namespace std;
Time::Time()
//default constructor. Initialize everything to start at 0
{
day = 0;
hour = 0;
minute = 0;
second = 0;
}
Time::Time(int s)
{
if (s < 0)
{
day = hour = minute = second = 0;
}
else
{
second = s;
day = second / 86400;
hour = (second / 3600) % 24;
minute = (second / 60) % 60;
second = second % 60;
}
}
Time::Time(int d, int h, int m, int s)
{
day = d;
hour = h;
minute = m;
second = s;
if (h < 0){
h = 0;
}
if (d < 0){
d = 0;
}
if (m < 0){
m = 0;
}
if (s < 0) {
s = 0;
}
}
ostream& operator<<(ostream& out, const Time& t)
{
out << t.day << "~";
if (0 <= t.hour && t.hour <= 10)
{
out << "0" << t.hour << ":";
}
else
out << t.hour << ":";
if (0 <= t.minute && t.minute <= 10)
{
out << "0" << t.minute << ":";
}
else
out << t.minute << ":";
if (0 <= t.second && t.second <= 10)
{
out << "0" << t.second;
}
else
out << t.minute;
return out;
}
另外,最后一个问题是,任何人都可以帮助运营商的操作员超载&gt;&gt;,我可以使用比较和添加运算符等等,但我不明白如何使用提取运营商。 我在努力 朋友istream&amp;运算符&gt;&gt;(istream&amp; in,const Time&amp; t); 在头文件中,但无法弄清楚在cpp文件的函数体中写入什么。任何帮助都会很棒
好的,我的链接问题已经解决了,我理解了提取运算符的作用。我会把它放在标题中......
friend istream& operator>>(istream& in, const Time& t);
和time.cpp
istream& operator>>(istream& in, const Time& t)
{
in >> t.day;
in >> t.hour;
in >> t.minute;
in >> t.second;
return in;
}
main.cpp测试文件有这个
cout << "Enter first Time object (DAYS~HH:MM:SS): ";
cin >> t1;
用户以(DAYS~HH:MM:SS)格式输入,所以只会说 在&gt;&gt; t.day;接受将在(DAYS)的价值,是这么简单吗?