本帖最后由 蛋蛋包子 于 2013-7-19 05:31 编辑
#km無論怎樣的看不懂啦....要求下面的那些題目調用了哪些構造函數(default,copy,destructor,assignment operator)
求大神能詳細指導一下麼?比如說在哪一句用了哪個構造函數
這個是前面的定義。問題有6個..class A{
public:
A();
A(const A&);
~A();
void operator = (const A&);
};
A::A(){cout<<"default constructor called\n";}
A::A(const A&){cout<<"copy constructor called\n";}
A::~A(){cout<<"destructor called\n";}
void A::operator=(const A& right_side){cout<<"assighnment operator called\n";}
第一個
用了default,但是求大神講解一下爲什麽只用了default...void foo(A& anobj){
cout<<"inside foo\n";
}
int main()
{
A thing;
foo(thing);
system("pause");
return 0;
}
第二個
這個用了default,copy,in side foo:copy,destructor,destructorA foo(A anobj){
cout<<"inside foo\n";
return anobj;
}
int main()
{
A thing;
foo(thing); //the returned object is destructed
system("pause");
return 0;
}
前面的一個default是main裏面的A thing這一句call出來的,copy的話是不是A foo(A anobj)這一句結束后call出來的還是說是在foo(thing)這裡?然後那個return的話是不是都要調用一個copy,所以在foo裏面有一個copy,然後題後面說了那個return後面的object會被刪掉,也就是說所以在return一完,就會有一個destru被call,然後整個foo run完,又調用一個destru 刪掉了一開始的一個copy。不知道這樣理解對不對...
第三個
default,copy,inside foo:copy,destructorA foo(A anobj){
cout<<"inside foo\n";
return anobj;
}
int main()
{
A thing;
A another=foo(thing);
system("pause");
return 0;
}
這個爲什麽只有一個destructor?就是說foo(thing)和A another=foo(thing)的各自作用到底是什麽...
第四個
default,copy。除了default就完全沒看懂了= =&這個符號在這裡是指的是地址還是說指的是reference..?A foo(A& anobj){
cout<<"inside foo\n";
return anobj;
}
int main()
{
A thing;
A another=foo(thing);
system("pause");
return 0;
}
第五個
default,default,copy,inside:destructor,assignment operator,destructorA foo(A anobj){
cout<<"inside foo\n";
return anobj;
}
int main()
{
A thing;
A another;
another=foo(thing);
system("pause");
return 0;
}
一開始的兩個default知道,copy的話不是很確定是在哪裡call出來的。assignment operator的話應該是another=foo(thing)這裡被call出來的吧。其他的都不知道是怎麼來的Orz
第六個
default,default,assignment operatorA& foo(A& anobj){
cout<<"inside foo\n";
return anobj;
}
int main()
{
A thing;
A another;
another=foo(thing);
system("pause");
return 0;
}
上面的inside foo後面的哪些constructor我不是能肯定到底是不是在foo裏面,答案只供參考= =還求大神指導之
超☆感☆謝大神
不過關於第五個,我是測試出來是那幾個constructor。
之後我查了查書,然後大概只有一個copy的原因應該是由於形參在函數結束的時候會被銷毀,因此系統會將返回的臨時賦值給一個對象。然後因為在main裏面another是之前就定義過了構造好了,所以是直接把值賦過去所以在return那裡就沒有用到copy,所以就在第一個dtor的時候銷毀的是一開始的一個copy,但是這樣的話第二個dtor就不知道是哪來的了...
system pause後面的constructor call應該是顯示不出來了才對....
[查看全文]
