C/C++/C#面試題精選

發表于:2011-03-09來源:作者:點擊數: 標簽:
題目(11):運行下圖中的C#代碼,輸出是什么? namespace StringValueOrReference { class Program { internal static void ValueOrReference(Type type) { String result = "The type " + type.Name; if (type.IsValueType) Console.WriteLine(result + " is

  題目(11):運行下圖中的C#代碼,輸出是什么?

  namespace StringValueOrReference

  {

  class Program

  {

  internal static void ValueOrReference(Type type)

  {

  String result = "The type " + type.Name;

  if (type.IsValueType)

  Console.WriteLine(result + " is a value type.");

  else

  Console.WriteLine(result + " is a reference type.");

  }

  internal static void ModifyString(String text)

  {

  text = "world";

  }

  static void Main(string[] args)

  {

  String text = "hello";

  ValueOrReference(text.GetType());

  ModifyString(text);

  Console.WriteLine(text);

  }

  }

  }

  答案:輸出兩行。第一行是The type String is reference type. 第二行是hello。類型String的定義是public sealed class String {...},既然是class,那么String就是引用類型。

  在方法ModifyString里,對text賦值一個新的字符串,此時改變的不是原來text的內容,而是把text指向一個新的字符串"world"。由于參數text沒有加ref或者out,出了方法之后,text還是指向原來的字符串,因此輸出仍然是"hello".

  題目(12):運行下圖中的C++代碼,輸出是什么?

  #include

  class A

  {

  private:

  int n1;

  int n2;

  public:

  A(): n2(0), n1(n2 + 2)

  {

  }

  void Print()

  {

  std::cout << "n1: " << n1 << ", n2: " << n2 << std::endl;

  }

  };

  int _tmain(int argc, _TCHAR* argv[])

  {

  A a;

  a.Print();

  return 0;

  }

  答案:輸出n1是一個隨機的數字,n2為0。在C++中,成員變量的初始化順序與變量在類型中的申明順序相同,而與它們在構造函數的初始化列表中的順序無關。因此在這道題中,會首先初始化n1,而初始n1的參數n2還沒有初始化,是一個隨機值,因此n1就是一個隨機值。初始化n2時,根據參數0對其初始化,故n2=0。

原文轉自:http://www.anti-gravitydesign.com

国产97人人超碰caoprom_尤物国产在线一区手机播放_精品国产一区二区三_色天使久久综合给合久久97