c#重载应用

来源:百度知道 编辑:UC知道 时间:2024/05/12 06:07:14
计算向量的,为了练习重载,为什么答案都是零啊????就是这样:
(3,4,5)+(5,6,7)=(0,0,0)
是不是类型转换的问题啊?

源程序
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
class Vector
{

public int d = 0, e = 0, f = 0;
public override string ToString()
{
return string.Format("({0},{1},{2})", d, e, f);
}

public int a=0, b=0, c=0, g=0;
public Vector(int a, int b, int c)
{
this.a = a;
this.b = b;
this.c = c;
}
public Vector(int g)
{
this.g = g;
}
public Vector()
{
}
public static Vector operator +(Vector v4, Vector v3)
{
return new Vector(v4.a + v3.a, v4.b + v3.b, v4.c + v3.c);
}

首先问你一下,你是不是要做出这种效果:
(3,4,5)+(5,6,7)=(8,10,12)
如果是继续往下,如果不是就不用看了.
大致的看了下代码
帮你分析了一下,注意,我只看了+方面的,-和*没看,你自己根据我+方面的改法改你的-和*

你重载了+运算符,想做出(3,4,5)+(5,6,7)=(8,10,12)这种效果

public Vector(int a, int b, int c)
{
this.a = a;
this.b = b;
this.c = c;
}
注意看上面这段,你在class Vector这个类里申明了public int a=0, b=0, c=0, g=0; this.a=a代表你申明的a=参数里的a,但你从未向传过任何参数进来,所以a,b,c一直保持为0;
下面是我改了一下的代码,只改了+号部份,其他未动,供你参考下,后面有注释为"\\被改过"的地方,代表那一行被我改过:
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
class Vector
{

public int d = 0, e = 0, f = 0;
public override string ToString()
{
return string.Format("({0},{1},{2})", d, e, f);
}

public int a=0, b=0, c=0, g=0;
public Vector(int a, int b, int c)
{
d = a; //被改过
e = b; //被改过
f = c; //被改过