在下面的c ++类中,我已经为构造函数提供了默认参数,以防用户没有提供。但是,当我Point2d1 first(1, 0);
中的main()
时,我得到一个没有匹配函数调用的错误。我期望将第3个参数默认为0的行为?
·H
#ifndef POINT2D1_H_
#define POINT2D1_H_
class Point2d1 {
private:
int m_Object_ID;
double m_x;
double m_y;
public:
//Point2d1(int nID);
Point2d1(int nID, double x, double y);
virtual ~Point2d1();
void print() const;
friend double distanceFrom(const Point2d1& D1, const Point2d1& D2);
};
#endif /* POINT2D1_H_ */
的.cpp
Point2d1::Point2d1(int nID = 0, double x = 0.0, double y = 0.0) : m_Object_ID(nID), m_x(x), m_y(y)
{
std::cout << "Constructing Point2d object " << nID << '\n';
}
Point2d1::~Point2d1() {
std::cout << "Destructing Object" << '\n';
}
void Point2d1::print() const
{
std::cout << "Point2d(" << m_x << ", " << m_y << ")\n";
}
double distanceFrom(const Point2d1& D1, const Point2d1& D2)
{
double distance = sqrt((D1.m_x - D2.m_x)*(D1.m_x - D2.m_x) + (D1.m_y - D2.m_y)*(D1.m_y - D2.m_y));
return distance;
}
答案 0 :(得分:2)
在头文件的类定义中声明成员函数声明中的默认参数。否则其他编译单元将不知道默认参数。
例如
<强>·H 强>
#ifndef POINT2D1_H_
#define POINT2D1_H_
class Point2d1 {
//...
public:
//Point2d1(int nID);
Point2d1(int nID = 0, double x = 0.0, double y = 0.0);
//...
};
#endif /* POINT2D1_H_ */
和
<强>的.cpp 强>
Point2d1::Point2d1(int nID, double x, double y) : m_Object_ID(nID), m_x(x), m_y(y)
{
std::cout << "Constructing Point2d object " << nID << '\n';
}