- 论坛徽章:
- 0
|
各位编程高手们:
最近我在学习C++,看到了复制构造函数这一块,遇到些问题,想请教一下大家,vc和vim中编写C++的一些区别,一下是源代码:我的困惑也在下面
#include <iostream>
#include <cstring>
using namespace std;
class mystring
{
char *s;
public:
mystring (char *str); //普通构造函数声明
mystring (const mystring &obj); //自定义复制构造函数声明
~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); //在此会调用普通构造函数
return ob; //在此会调用自定义复制构造函数
}
int main (void)
{
mystring obj = input (); //调用自定义复制构造函数
obj.show ();
return 0;
}
本应该的运行结果是:
Please input a string : hello
Normal constructor called.
Copy constructor called.
Freeing s.
hello
Freeing s.
在vc中的运行结果确实也是这样,但是在linux下,运行的结果却是没有调用复制构造函数:
Please input a string : hello
Normal constructor called.
hello
Freeing s.
我有些困惑,出现这样的结果是因为编译环境的问题么?还是其他原因?
如果想让程序运行出预想的结果应该怎么做?
我的描述可能不太准确,因为刚刚开始学习的。。
谢谢大家先。。 |
|