題目(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。類(lèi)型String的定義是public sealed class String {...},既然是class,那么String就是引用類(lèi)型。
在方法ModifyString里,對text賦值一個(gè)新的字符串,此時(shí)改變的不是原來(lái)text的內容,而是把text指向一個(gè)新的字符串"world"。由于參數text沒(méi)有加ref或者out,出了方法之后,text還是指向原來(lái)的字符串,因此輸出仍然是"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是一個(gè)隨機的數字,n2為0。在C++中,成員變量的初始化順序與變量在類(lèi)型中的申明順序相同,而與它們在構造函數的初始化列表中的順序無(wú)關(guān)。因此在這道題中,會(huì )首先初始化n1,而初始n1的參數n2還沒(méi)有初始化,是一個(gè)隨機值,因此n1就是一個(gè)隨機值。初始化n2時(shí),根據參數0對其初始化,故n2=0。
文章來(lái)源于領(lǐng)測軟件測試網(wǎng) http://kjueaiud.com/