【发布时间】:2019-04-26 19:05:45
【问题描述】:
我了解错误对应的内容...我无法理解的是它们出现在我的代码中的方式。
错误信息: 错误(活动)E0339 类“Point”有多个默认构造函数
错误 C2512 'Line':没有合适的默认构造函数可用
main.cpp
Point p1, p2;
Line line(p1, p2);
cout << "Point 1\n";
line.set_point1();
cout << "Point 2\n";
line.set_point2();
line.print();
source.cpp
Point::Point() : x(0), y(0) { cout << "Point created\n"; }
Point::Point(double tx = 0, double ty = 0) : x(tx), y(ty) { cout << "Point created\n"; }
Point::Point(const Point& tobj) : x(tobj.x), y(tobj.y) { cout << "Point copied\n"; }
Point::~Point() { cout << "Point destroyed\n"; }
void Point::set_x() { cin >> x; }
void Point::set_y() { cin >> y; }
double Point::get_x() const { return x; }
double Point::get_y() const { return y; }
void Point::print() const { cout << "Point -- (" << x << " , " << y << ")\n"; }
Line::Line() { cout << "Line created\n"; } //CLASS "POINT" HAS MORE THAN ONE DEFAULT CONSTRUCTOR
Line::Line(const Point& tp1, const Point& tp2) : p1(tp1), p2(tp2) { cout << "Line created\n"; }
Line::Line(const Line& tobj) : p1(tobj.p1), p2(tobj.p2) { cout << "Line copied\n"; }
Line::~Line() { cout << "Line destroyed\n"; }
void Line::set_point1() { p1.set_x(); p1.set_y(); }
void Line::set_point2() { p2.set_x(); p2.set_y(); }
double Line::get_slope() { return ((p2.get_y() - p1.get_y()) / (p2.get_x() - p1.get_x())); }
void Line::print() { cout << "Point 1 == "; p1.print(); cout << "Point 2 == "; p2.print(); cout << "Slope == " << get_slope() << endl; }
header.h
class Point
{
double x, y;
public:
Point();
Point(double, double);
Point(const Point&);
~Point();
void set_x();
void set_y();
double get_x() const;
double get_y() const;
void print() const;
};
class Line
{
Point p1, p2;
public:
Line();
Line(const Point&, const Point&);
Line(const Line&);
~Line();
void set_point1();
void set_point2();
double get_slope();
void print();
};
当我删除 Line::Line() { ... } 时,一切正常。主要问题是这样的:
1 - 为什么这一行会触发 POINT 类的错误消息。
2 - 为什么会触发“...多个默认构造函数”
3 - 为什么会触发“对重载函数的模糊调用”
我正在尝试创建不带任何参数的 Line 对象,就像 Line line; 一样
【问题讨论】:
-
请添加整个错误消息和错误函数的主体。并删除了
.和...,这使得无法在编译器中复制/粘贴代码。 -
Point(double tx = 0, double ty = 0)提供了 2 个默认参数 - 它与Point()构造函数有何不同? -
@UnholySheep 是对的。在您的
main.cpp中,对Point()的调用并不含糊,因为声明Point(double, double)没有默认参数,但在source.cpp中,构造函数Line()同时看到Point()和Point(double = 0, double = 0),因此出现了模棱两可的重载. -
@UnholySheep 啊....你不会相信我花了多少时间试图弄清楚它,因为我在想 Line 类中的某些东西正在触发它....谢谢先生,抱歉耽误您的时间
标签: c++ visual-studio