问题描述
函数调用中的参数太少?这段代码有什么问题? 我想输出到 std::cout 日
#include <iostream>
#include <string>
class Date
{
public:
Date(unsigned _day,unsigned _month,unsigned _year) : day(_day),month(_month),year(_year) {}
int GetDate(Date& dt)
{
return dt.day;
}
private:
unsigned day,month,year;
};
int main()
{
Date dt(07,10,2004);
std::cout << dt.GetDate();
return 0;
std::cin.get();
}
我明白原理但不知道该怎么做
/*too few arguments in function call
Error C2660 'Date::GetDate': function does not take 0 arguments */
解决方法
作为这个成员函数
int GetDate(Date& dt)
{
return dt.day;
}
是一个非静态成员函数,那么当它输出调用它的对象的数据成员日期时是很自然的。但它是用一个参数定义的,该参数接受另一个 Date
类型的对象。
因此在这个函数调用中
std::cout << dt.GetDate();
您需要指定类型为 Date
的参数,例如
Date dt(07,10,2004);
std::cout << dt.GetDate( dt );
但这没有多大意义。
函数应该在类中定义
int & GetDate()
{
return day;
}
超载
const int & GetDate() const
{
return day;
}
在这种情况下这个代码片段
Date dt(07,2004);
std::cout << dt.GetDate();
会有意义。
尽管将函数命名为 GetDay
会更好。
注意这个声明
std::cin.get();
没有效果,因为它放在 return 语句之后。也许你的意思
std::cin.get();
return 0;
,
您已将 GetDate()
定义为 Date
类的非静态方法,并将显式 Date&
对象引用作为参数。但是 main()
没有将 Date
对象传递到该参数中,因此出现错误。
不需要显式传入对象。作为非静态方法,GetDate()
有一个隐藏的 this
参数,该参数引用 Date
被调用的 GetDate()
对象。
试试这个:
#include <iostream>
#include <string>
class Date
{
public:
Date(unsigned _day,unsigned _month,unsigned _year) : day(_day),month(_month),year(_year) {}
int GetDate() const
{
return day; // this->day
}
private:
unsigned day,month,year;
};
int main()
{
Date dt(07,2004);
std::cout << dt.GetDate();
return 0;
std::cin.get();
}
,
理想情况下,您应该更新 GetDate
函数的实现。
int GetDate()
{
return day;
}
,
函数 GetDate 有一个参数,您没有在函数 main 中传递该参数。
应该是
Date a(1,1,2001);
std::cout << dt.GetDate(a);