这段C++代码有错求各位解答


#include <iostream>
using namespace std;
 
class test
{
        double x, y, z;
    public:
        test(double x, double y, double z): x(x), y(y), z(z) {}
        double operator * (test A, test B);
};
 
double operator * (test A, test B)
{
    return A.x * B.x + A.y * B.y + A.z * B.z;
}
 
int main()
{
    test A(1, 2, 3);
    test B(3, 2, 1);
    cout << "vector A*B=" << A*B << endl;
}

此代码有错,求各位解答

两个问题:

  • 在类外定义重载运算符 * 时,应该将其声明为该类的友元函数。
  • 友元函数只需要一个参数,因为第一个参数已经是该类的对象了。

修改后的代码:

#include <iostream>
using namespace std;
 
class test
{
    double x, y, z;
public:
    test(double x, double y, double z): x(x), y(y), z(z) {}
    friend double operator * (test A, test B);
};
 
double operator * (test A, test B)
{
    return A.x * B.x + A.y * B.y + A.z * B.z;
}
 
int main()
{
    test A(1, 2, 3);
    test B(3, 2, 1);
    cout << "vector A*B=" << A*B << endl;
    return 0;
}

operator* 只能有一个参数。

#include <iostream>

using namespace std;

class test
{
    double x, y, z;
public:
    test(double x, double y, double z) : x(x), y(y), z(z)
    {
    }

    double operator*(test B);
};

double test::operator*(test B)
{
    return x * B.x + y * B.y + z * B.z;
}

int main()
{
    test A(1, 2, 3);
    test B(3, 2, 1);
    cout << "vector A*B=" << A * B << endl;
}