- 論壇徽章:
- 0
|
各位編程高手們:
最近我在學習C++,看到了復制構造函數(shù)這一塊,遇到些問題,想請教一下大家,vc和vim中編寫C++的一些區(qū)別,一下是源代碼:我的困惑也在下面
#include <iostream>
#include <cstring>
using namespace std;
class mystring
{
char *s;
public:
mystring (char *str); //普通構造函數(shù)聲明
mystring (const mystring &obj); //自定義復制構造函數(shù)聲明
~mystring ()
{
if (s)
delete [] s;
cout << "Freeing s\n";
}
void show ()
{
cout << s << "\n";
}
};
mystring::mystring (char *str)
{
s = new char[strlen(str) + 1];
cout << "Normally constructor called\n";
strcpy (s, str);
}
mystring::mystring (const mystring &obj)
{
s = new char[strlen(obj.s) + 1];
cout << "Copy constructor called \n";
strcpy (s, obj.s);
}
mystring input ()
{
char instr[80];
cout << "Please input a string:";
cin >> instr;
mystring ob (instr); //在此會調用普通構造函數(shù)
return ob; //在此會調用自定義復制構造函數(shù)
}
int main (void)
{
mystring obj = input (); //調用自定義復制構造函數(shù)
obj.show ();
return 0;
}
本應該的運行結果是:
Please input a string : hello
Normal constructor called.
Copy constructor called.
Freeing s.
hello
Freeing s.
在vc中的運行結果確實也是這樣,但是在linux下,運行的結果卻是沒有調用復制構造函數(shù):
Please input a string : hello
Normal constructor called.
hello
Freeing s.
我有些困惑,出現(xiàn)這樣的結果是因為編譯環(huán)境的問題么?還是其他原因?
如果想讓程序運行出預想的結果應該怎么做?
我的描述可能不太準確,因為剛剛開始學習的。。
謝謝大家先。。 |
|