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

g++编译C++代码报arm64架构未定义符号错误求助

问题解决方法

直接解决当前链接报错

你现在遇到的Undefined symbols是典型的链接错误,原因是编译时没有将vector2d.cpp一起参与编译链接,链接器找不到v2d类成员函数的实现。
正确的编译命令为:

g++ main.cpp vector2d.cpp -o vector_test

执行上述命令即可解决当前的链接报错问题。但此时你的代码仍无法得到正确运行结果,因为类成员函数和运算符重载的实现存在逻辑与规范错误,需要按以下步骤修正。

修正代码逻辑错误

1. 运算符重载规范修正

你当前的operator+、operator*(double)返回值为自身引用,不符合向量运算的常规逻辑:加法和数乘运算不会修改原向量,应该返回新的向量对象,同时所有不修改类成员的函数需要加const修饰保证const正确性。

首先更新vector2d.h的类声明:

#ifndef __v2d__
#define __v2d__

class v2d {
public:
    // 标准构造函数
    v2d(double a, double b);
    // 拷贝构造函数
    v2d(const v2d & v);
    // 析构函数
    ~v2d(void);

    // 赋值运算符
    v2d & operator=(const v2d &v);
    // 向量加法,返回新向量
    v2d operator+(const v2d &v) const;
    // 数乘运算,返回新向量
    v2d operator*(double k) const;
    // 向量点乘
    double operator*(const v2d &v) const;
    // 求向量长度
    double length(void) const;

private:
    double x;
    double y;
};
#endif

2. 补全vector2d.cpp的函数实现

#include "vector2d.h"
#include <cmath>

v2d::v2d(double a, double b) : x(a), y(b) {}

v2d::v2d(const v2d & v) : x(v.x), y(v.y) {}

v2d::~v2d() {}

v2d & v2d::operator=(const v2d &v) {
    if (this != &v) {
        x = v.x;
        y = v.y;
    }
    return *this;
}

v2d v2d::operator+(const v2d &v) const {
    return v2d(x + v.x, y + v.y);
}

double v2d::operator*(const v2d &v) const {
    return x * v.x + y * v.y;
}

v2d v2d::operator*(double k) const {
    return v2d(x * k, y * k);
}

double v2d::length() const {
    return sqrt(x * x + y * y);
}

3. 运行测试

main.cpp无需修改,再次执行编译命令后运行程序,将得到预期输出:

Pythagoras holds on perpendicular triangles (a,b,c):
a = 3 , b = 4 , c = 5
...but not on non-perpendicular triangles (a,b,c):
a = 3.60555 , b = 4 , c = 3.60555

内容的提问来源于stack exchange,提问作者Lukas Guldstøv

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 18:09:01