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

如何让C++的point类支持单参数构造,适配point b(-3)写法?

解决point类适配单参数构造的问题

要让代码支持point b(-3)的写法,只需给point类新增一个单参数构造函数,同时可以优化move函数的返回值以提升效率,修改后的完整代码如下:

#include <iostream>

using namespace std;

class point {
private:
    int x, y;
public:
    point(int x, int y) : x(x), y(y) {}
    // 新增单参数构造函数,默认将y初始化为0
    point(int x) : x(x), y(0) {}

    // 修改返回值为point&,避免临时对象拷贝,链式调用更高效
    point& move(const point &p) {
        x += p.x;
        y += p.y;
        return *this;
    }

    void print() {
        cout << "(" << x << ", " << y << ")" << endl;
    }
};

int main() {
    point a(2, 1), b(-3);
    a.move(b).print(); // 运行后输出(-1, 1)
}

关键修改说明:

  • 单参数构造函数:新增的point(int x)构造函数,在只传入一个整数参数时自动将y成员初始化为0,完美适配point b(-3)的写法,满足题目要求的构造方式。
  • move函数返回值优化:将返回值从point改为point&,返回当前对象的引用,这样在链式调用a.move(b).print()时不会产生额外的对象拷贝,既保证逻辑正确性(修改的是a本身),又提升了代码效率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 01:25:27