[問題] 關於"運算子overloading"的問題
定義了一些運算子多載,
使用的時候發現2個問題,
其一是我的程式不允許我使用"連續技",
Ex: (A+B)/C 類似的用法
其二就直接請大家幫我看看程式碼了,以下函式出了錯?
double distance(Point p1, Point p2)
#include <iostream>
#include <cstdlib>
#include <cmath>
using namespace std;
struct Point {double x,y,z;};
struct Vector {double x, y, z;};
double distance(Point p1, Point p2)
{
return sqrt((p2.x-p1.x)*(p2.x-p1.x) + (p2.y-p1.y)*(p2.y-p1.y) +
(p2.z-p1.z)*(p2.z-p1.z));
}
Vector operator*(Vector &v, double n)
{
Vector u = {v.x*n, v.y*n, v.z*n};
return u;
}
Vector operator+(Vector &v1, Vector &v2)
{
Vector v={(v1.x + v2.x), (v1.y + v2.y), (v1.z + v2.z) };
return v;
}
Vector operator/(Vector &v, double n)
{
Vector u = {v.x/n, v.y/n, v.z/n};
return u;
}
Vector operator+(Point &p, Vector &v)
{
Vector u = {p.x + v.x, p.y + v.y, p.z + v.z};
return u;
}
Vector operator-(Point &p1, Vector &v1)
{
Vector v={p1.x-v1.x, p1.y-v1.y, p1.z-v1.z};
return v;
}
int main()
{
// Test1
Point i = {9, 9, 9};
Point j = {-1, -1, -1};
double a = distance(i,j); // 出錯了
// Test2
Vector b = {2,2,2};
Vector d = b/2;
Vector e = (b/2) + b; // 出錯了
Vector f = d + b;
// Test3
Vector A = {1,1,1};
Vector B = {2,2,2};
Vector C = (A+B) -B; // 出錯了
// Test4
Vector D = i+A;
system("pause");
return 0;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.120.11.63
→
05/10 10:41, , 1F
05/10 10:41, 1F
推
05/10 11:03, , 2F
05/10 11:03, 2F
→
05/10 11:03, , 3F
05/10 11:03, 3F
→
05/10 11:04, , 4F
05/10 11:04, 4F
推
05/10 11:14, , 5F
05/10 11:14, 5F
→
05/10 11:15, , 6F
05/10 11:15, 6F
→
05/10 11:16, , 7F
05/10 11:16, 7F
→
05/10 11:16, , 8F
05/10 11:16, 8F
→
05/10 11:17, , 9F
05/10 11:17, 9F
→
05/10 15:10, , 10F
05/10 15:10, 10F
→
05/10 15:36, , 11F
05/10 15:36, 11F
→
05/10 15:36, , 12F
05/10 15:36, 12F
推
05/10 15:40, , 13F
05/10 15:40, 13F
→
05/10 15:41, , 14F
05/10 15:41, 14F
→
05/10 15:41, , 15F
05/10 15:41, 15F
→
05/10 16:39, , 16F
05/10 16:39, 16F
→
05/10 16:39, , 17F
05/10 16:39, 17F
→
05/13 02:18, , 18F
05/13 02:18, 18F