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

planeVector类使用double类型时多对象创建异常问题求助

问题分析与解决

核心错误原因

程序崩溃的根本原因是析构函数中错误使用delete释放非动态分配的成员变量:

~planeVector()
{
    delete &x;
    delete &y;
}

成员变量x和y是类的内置成员,它们的内存随对象一起分配(栈或堆空间),并非通过new动态申请。delete仅能用于释放new返回的指针,对非动态内存执行delete会触发未定义行为,直接导致程序无预警终止。

解决方案

直接删除析构函数中的delete语句,甚至可以完全移除自定义析构函数——编译器会自动生成默认析构函数,足以处理这类简单成员的销毁逻辑。

修正后的planevector.cpp代码:

#include <cmath>
#include <string>
using namespace std;

class planeVector
{
    double x;
    double y;
public:
    planeVector(int x = 0, int y = 0)
    {
        this->x = x;
        this->y = y;
    }

    // 移除错误的析构函数,或保留空析构函数(可选)
    // ~planeVector() {}

    void operator+=(planeVector vec)
    {
        this->x += vec.x;
        this->y += vec.y;
    }

    void operator-=(planeVector vec)
    {
        this->x -= vec.x;
        this->y -= vec.y;
    }

    void operator*=(double num)
    {
        this->x *= num;
        this->y *= num;
    }

    void operator/=(double num)
    {
        this->x /= num;
        this->y /= num;
    }

    planeVector operator+(planeVector vec)
    {
        return planeVector(this->x + vec.x, this->y + vec.y);
    }

    planeVector operator-(planeVector vec)
    {
        return planeVector(this->x - vec.x, this->y - vec.y);
    }

    planeVector operator/(double num)
    {
        return planeVector(this->x / num, this->y / num);
    }

    planeVector operator*(double num)
    {
        return planeVector(this->x * num, this->y * num);
    }

    void normalize()
    {
        (*this) /= this->mag();
    }

    double mag()
    {
        return pow(this->x * this->x + this->y * this->y, 0.5); 
    }

    operator std::string() const
    {
        return "(" + std::to_string(this->x) + ", " + std::to_string(this->y) + ")";   
    }
};

额外优化建议

  1. 避免直接包含cpp文件:将planeVector的声明放在头文件(如planevector.h),实现放在planevector.cpp,main中仅包含头文件,防止重复定义问题。
  2. 构造函数类型对齐:把构造函数参数改为double类型,避免不必要的隐式转换:
    planeVector(double x = 0.0, double y = 0.0) : x(x), y(y) {}
    
  3. 使用初始化列表:构造函数优先用初始化列表初始化成员变量,比赋值操作更高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 19:05:10