#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;
}