gcc和vs08下编译结果不一样,大家能否解释下这两个程序原理?
程序A:#include<iostream>
#include<string>
using namespace std;
using std::string;
class Student
{
public:
Student(void);
Student(int num, string name, char sex);
~Student(void);
void Display(void);
private:
int m_num;
string m_name;
char m_sex;
};
Student::Student(void)
{
m_num = 1001;
m_name = "Brian";
m_sex = 'M';
cout << "DefaultConstructor" << endl;
}
Student::Student(int num, string name, char sex) : m_num(num), m_name(name), m_sex(sex)
{
cout << "Constructor" << m_name << endl;
}
Student::~Student(void)
{
cout << "Destructor" << m_name << endl;
getchar();
}
void Student::Display(void)
{
cout << "num: " << m_num << '\n';
cout << "name: " << m_name << '\n';
cout << "sex: " << m_sex << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
Student stud[2] = {Student(1002, "lisa", 'F'), };
stud[0].Display();
stud[1].Display();
getchar();
return 0;
}
结果是:
Constructorlisa
Destructorlisa
DefaultConstructor
num: 1002
name: lisa
sex: F
num: 1001
name: Brian
sex: M
DestructorBrian
Destructorlisa
程序B:
#include<iostream>
using namespace std;
class A
{
public:
A();
A(int x);
~A() { cout << "destructor called" << itsnumber << endl;getchar();}
private:
int itsnumber;
};
A::A()
{
itsnumber=5;
cout << "constructor called" << itsnumber<< endl;
getchar();
}
A::A(int x)
{
itsnumber=x;
cout << "constructor called" << itsnumber << endl;
getchar();
}
int _tmain(int argc, _TCHAR* argv[])
{
A a[2]={A(8),};
getchar();
return 0;
}
运行结果是:
constructor called8
constructor called5
destructor called5
destructor called8
网上有人说有个对象的临时拷贝,但这样的话程序A和B是说不通的,望高人指点。
[ 本帖最后由 grow 于 2010-9-22 15:28 编辑 ]