代码:
#include <iostream>
#include <cstring>
using namespace std;
class Student{
public:
Student(char* pName="no name",int ssId=0)
{
strncpy(name,pName,40);
name[39]='\0';
id = ssId;
cout <<"Constructing new student " <<pName <<endl;
}
Student(Student& s)
{
cout<<"Constructing copy of "<<s.name<<endl;
strcpy(name,"copy of ");
strcat(name,s.name);
id=s.id;
}
void show(){
cout<<"name="<<name<<" ,id="<<id<<endl;
}
~Student(){
cout <<"Destructing " <<name <<endl;
}
protected:
char name[40];
int id;
};
void fn(Student s)
{
cout <<"into function fn()\n";
s.show();
cout<<"out of function fn()\n";
}
int main()
{
Student randy("Randy",1234);
Student elizabeth=randy;
Student &refs=Student("beijing",2345);
Student s=Student("shanghai",5678);
fn(Student("guangzhou",2345));
return 1;
}
在VC++6.0上的编译运行结果是:
Constructing new student Randy
Constructing copy of Randy
Constructing new student beijing
Constructing new student shanghai
Constructing new student guangzhou
into function fn()
name=guangzhou ,id=2345
out of function fn()
Destructing guangzhou
Destructing shanghai
Destructing beijing
Destructing copy of Randy
Destructing Randy
但是在linux g++上却编译通不过,一直提示
Student &refs=Student("beijing",2345);
Student s=Student("shanghai",5678);
fn(Student("guangzhou",2345));
这三个函数没有匹配的可调用函数。是不是linux g++不支持无名对象?看来linux g++和VC++的C++编译器差别好大。
分析:
上面代码中Student("beijing",2345) , Student("shanghai",5678) 和 Student("guangzhou",2345)都是没有对象名的对象,所以叫做无名对象,无名对象和复制拷贝并没有关系,所以不会调用拷贝构造函数,
Student &refs=Student("beijing",2345);等同于Student refs("beijing",2345);
Student s=Student("shanghai",5678);等同于Student s("shanghai",5678);
fn(Student("guangzhou",2345));等同于下面两句:
Student x("guangzhou",2345);
fn(x);
无名对象最大的好处在于对象初始化的时候,不会调用拷贝构造函数。对于比较大的对象实体可以采用这样的方式进行初始化,是一种好的编程习惯。