undefined reference to `Class::Function() / error: Id returned 1 exit status
undefined reference to `Class::Function() / error: Id returned 1 exit status
我正在尝试初始化值,我遵循 Bjarne Stroustrup 的书,但不能 运行 此代码。
#include <iostream>
using namespace std;
struct Date
{
int y, m, d; // year, month, day
Date(int y, int m, int d); // check for valid & initialize
void add_day(int n); // increase the Date by n days
};
int main()
{
Date today(2021, 1, 6);
return 0;
}
这里是错误:
undefined reference to `Date::Date(int, int, int)'
collect2.exe: error: ld returned 1 exit status
在 C++ 编程语言中,您可以像定义一个 class 一样定义一个结构。您收到错误的原因是您没有严格定义方法。
#include <iostream>
using namespace std;
struct Date
{
/* fields */
int _year, _month, _day;
/* constructor */
Date(int year, int month, int day) : _year(year), _month(month), _day(day){}
/* setter method */
void add_day(int n)
{
/* You need to develop an algorithm to keep track of the end of the month and the year. */
_day += n;
}
/* getter method */
int get_day()
{
return _day;
}
};
int main()
{
Date today(2021, 1, 6);
today.add_day(1);
cout << today.get_day() << endl;
return 0;
}
我正在尝试初始化值,我遵循 Bjarne Stroustrup 的书,但不能 运行 此代码。
#include <iostream>
using namespace std;
struct Date
{
int y, m, d; // year, month, day
Date(int y, int m, int d); // check for valid & initialize
void add_day(int n); // increase the Date by n days
};
int main()
{
Date today(2021, 1, 6);
return 0;
}
这里是错误:
undefined reference to `Date::Date(int, int, int)'
collect2.exe: error: ld returned 1 exit status
在 C++ 编程语言中,您可以像定义一个 class 一样定义一个结构。您收到错误的原因是您没有严格定义方法。
#include <iostream>
using namespace std;
struct Date
{
/* fields */
int _year, _month, _day;
/* constructor */
Date(int year, int month, int day) : _year(year), _month(month), _day(day){}
/* setter method */
void add_day(int n)
{
/* You need to develop an algorithm to keep track of the end of the month and the year. */
_day += n;
}
/* getter method */
int get_day()
{
return _day;
}
};
int main()
{
Date today(2021, 1, 6);
today.add_day(1);
cout << today.get_day() << endl;
return 0;
}