C++创建含两个double值的Point2D类:请帮忙排查代码错误
Hey there, let's fix the issues in your code one by one:
Key Issues Found:
Incorrect parameterized constructor definition (in
Point2D.cpp):
You named the parameterized constructorsP1andP2, which violates C++ constructor rules—constructors must match the exact name of their class. You also duplicated the constructor unnecessarily; only one parameterized constructor is needed per your requirements.Variable assignment typo (in
TestCheckPoint1.cpp):
When setting values forPoint2, you accidentally assigned2.0toPoint1.yinstead ofPoint2.y. This leavesPoint2.ystuck at its default 0.0 value, which isn't what you intended.
Corrected Code:
Point2D.cpp
#include "Point2D.h" #include <iostream> using namespace std; // Default constructor (works as is, can be optimized later) Point2D::Point2D() { x = 0.0; y = 0.0; } // Fixed parameterized constructor name to match the Point2D class Point2D::Point2D(double in_x, double in_y) { x = in_x; y = in_y; } void GetResult(Point2D P1, Point2D P2) { cout << P1.x << " " << P1.y << endl; cout << P2.x << " " << P2.y << endl; }
TestCheckPoint1.cpp
#include <iostream> #include "Point2D.h" using namespace std; int main() { Point2D Point1; Point1.x = 1.0; Point1.y= 2.0; Point2D Point2; Point2.x= 1.0; // Fixed the variable name here to assign to Point2's y value Point2.y= 2.0; GetResult(Point1, Point2); }
Optional Optimization:
For cleaner and more efficient code, use member initializer lists for your constructors instead of assigning values inside the constructor body. This directly initializes members rather than default-initializing them first then reassigning:
Point2D::Point2D() : x(0.0), y(0.0) {} Point2D::Point2D(double in_x, double in_y) : x(in_x), y(in_y) {}
内容的提问来源于stack exchange,提问作者Naq Z

