You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 constructors P1 and P2, 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 for Point2, you accidentally assigned 2.0 to Point1.y instead of Point2.y. This leaves Point2.y stuck 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:35:09