首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

C#的两个简单有关问题

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

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的时候程序是怎样执行的? 

----
先执行基类的构造函数,再扩行派生类的构造函数,基类构造函数就进行输出的时候,你的y还没有初始化,所以为0



[解决办法]

为什么b1会输出false bool bl = (ch0 == ch1); 问题在哪? 


 ---------------------

问题在这里
ch3 = ch1 + ch2; 
ch1为引用类型,在这里你重载的加法.实际已经改变了你ch1对象的值.所以ch1已经不为其初始值了

在这里你的ch1==ch3的.你不信可以输出试试看
[解决办法]

try

C# code
public   static   chongzai   operator   +(chongzai   ch1,   chongzai   ch2)                 {                         chongzai result=new chongzai();                        result.x=ch1.x+ch2.x;                        result.y=ch1.y+ch2.y;                        result.z=ch1.z+ch2.z;                        return   result;                 } 

热点排行