日期:2014-05-18  浏览次数:20819 次

C#的两个简单问题
刚学习C#,希望高手多多指教!
第一个问题:
 class test
  {
  static void Main(string[] args)
  {
  B b = new B();

  }
  }

  class A
  {
  public A()
  {
  PrintFields();
  }
  public virtual void PrintFields() { }
  }
  class B : A
  {
  int x = 1;
  int y;
  public B()
  {
  y = -1;
  }
  public override void PrintFields()
  {
  Console.WriteLine("x={0},y={1}", x, y);
  }
  }

为什么输出的结果是:x=1,y=0
当实例化B的时候程序是怎样执行的?


第二个问题:

class chongzai
  {
  private double x;
  private double y;
  private double z;
  public chongzai()
  {
  x = 0;
  y = 0;
  z = 0;
  }
  public chongzai(double x, double y, double z)
  {
  this.x = x;
  this.y = y;
  this.z = z;
  }
  public chongzai(chongzai ch)
  {
  x = ch.x;
  y = ch.y;
  z = ch.z;
  }

  public static chongzai operator +(chongzai ch1, chongzai ch2)
  {
  ch1.x += ch2.x;
  ch1.y += ch2.y;
  ch1.z += ch2.z;
  return ch1;

  }
  public override string ToString()
  {
  return "x的坐标是" + x + "y的坐标是" + y + "z的坐标是" + z;
  }
  public static bool operator ==(chongzai ch1, chongzai ch2)
  {
  if (ch1.x == ch2.x && ch1.y == ch2.y && ch1.z == ch2.z)
  {
  return true;
  }
  else
  {
  return false;
  }
   
  }

  public static bool operator !=(chongzai ch1, chongzai ch2)
  {
  return !(ch1 == ch2);
   
  }
  static void Main(string[] args)
  {
  chongzai ch0 = new chongzai(1, 2, 3);
  chongzai ch1 = new chongzai(1, 2, 3);
  Console.WriteLine(ch1.ToString());
  chongzai ch2 = new chongzai(ch1);
  Console.WriteLine(ch2.ToString());
  chongzai ch3;
  ch3 = ch1 + ch2;
  bool bl = (ch0 == ch1);
  Console.WriteLine(bl);
  if (ch1 == ch2)
  {
  Console.WriteLine("you are right,they are equal");
  }
  else
  {
  Console.WriteLine("they are not equal");
  }
  Console.WriteLine(ch3.ToString());


  }
  }

那个比较运算符重载有问题,为什么b1会输出false bool bl = (ch0 == ch1); 问题在哪?
恳请热心人帮忙解答,谢谢啦!


------解决方案--------------------
为什么输出的结果是:x=1,y=0 
当实例化B的时候程序是怎样执行的?