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

C++类引用传递问题:无法正确获取Point类私有成员变量值

C++ Point类坐标获取功能修复

问题场景

现有代码中,Point类的get方法无法正确返回对象的坐标值,调用后输出未初始化的垃圾值(如-9.25596e+61),而非预期的初始化坐标10.5, 20.99。

错误原因

  1. getx/gety函数无有效赋值逻辑:函数内仅写了x;或y;,这是无意义的表达式,并未将类私有成员的坐标值传递给传入的引用参数。
  2. 参数名与类成员名重名:getx的参数x和类私有成员x同名,即使写赋值语句也会优先访问局部参数,无法正确引用类成员变量。

修复后的代码

main.cpp(无需修改)

#include "Point.h"
#include <iostream>
using namespace std;

int main(void) {
    double x, y;
    Point p{ 10.5, 20.99 };
    p.info();
    p.get(x, y);
    cout << x << ", " << y << endl;
    return 0;
}

Point.h(修改核心逻辑)

#include <iostream>
using namespace std;
class Point {
private:
    double x, y;
public:
    Point(double P_x , double P_y) {
        x = P_x;
        y = P_y;
    }
    void info(void) {
        cout << "(x,y) = " << x << ", " << y << endl;
    }
    // 修改getx:用this->区分成员变量,完成赋值
    void getx(double &x) {
        x = this->x;
    }
    // 修改gety:同理完成赋值,移除无意义的返回值
    void gety(double &y) {
        y = this->y;
    }
    void get(double& x, double& y) {
        getx(x);
        gety(y);
    }
};

简化优化方案(可选)

直接合并get方法逻辑,减少冗余代码:

void get(double& x, double& y) {
    x = this->x;
    y = this->y;
}

验证结果

运行修复后的代码,输出符合预期:

(x,y) = 10.5, 20.99
10.5, 20.99

内容的提问来源于stack exchange,提问作者user20344215

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 09:25:24