主题:[讨论]运算符重载问题。
#include<iostream.h>
#include<string.h>
class String
{
char name[256];
public:
String(char *str)
{
cout<<"constructor,char* ->string\n";
strcpy(name,str);
}
String(String &s)
{
cout<<"copy constructor\n";
strcpy(name,s.name);
}
String(){cout<<"default constructor\n";}
~String(){}
String operator +(const String&);
void operator =(const String&s)
{
strcpy(name,s.name);
cout<<"operator="<<endl;
}
void display()
{
cout<<"the string is:"<<name<<endl;
}
};
static char* str;
String String::operator+(const String& a)
{
String s;
cout<<"operator +"<<endl;
strcpy(s.name,name);
strcat(s.name,a.name);
return s;
}
void main()
{
str=new char[256];
String demo1("visual c++");
String demo2("6.0");
demo1.display();
demo2.display();
String demo3;
demo3=demo1+demo2;
demo3.display();
}
红色部分不明白:在创建demo3的时候已经调用过了对象的构造函数,为什么执行下一句代码时候再一次调用对象构造函数呢?
#include<string.h>
class String
{
char name[256];
public:
String(char *str)
{
cout<<"constructor,char* ->string\n";
strcpy(name,str);
}
String(String &s)
{
cout<<"copy constructor\n";
strcpy(name,s.name);
}
String(){cout<<"default constructor\n";}
~String(){}
String operator +(const String&);
void operator =(const String&s)
{
strcpy(name,s.name);
cout<<"operator="<<endl;
}
void display()
{
cout<<"the string is:"<<name<<endl;
}
};
static char* str;
String String::operator+(const String& a)
{
String s;
cout<<"operator +"<<endl;
strcpy(s.name,name);
strcat(s.name,a.name);
return s;
}
void main()
{
str=new char[256];
String demo1("visual c++");
String demo2("6.0");
demo1.display();
demo2.display();
String demo3;
demo3=demo1+demo2;
demo3.display();
}
红色部分不明白:在创建demo3的时候已经调用过了对象的构造函数,为什么执行下一句代码时候再一次调用对象构造函数呢?