我需要帮助在面向对象的程序中执行这个拷贝构造函数。结果应该是将字符串1:Hello World
复制到字符串2:This is a test
。使用.Copy执行复制构造函数的最佳方法是什么?
在我.h
文件:
void Copy(MyString& one);
在我.cpp
文件:
void MyString::Copy(MyString& one)
{
one = String;
}
在我main.cpp
文件:
String1.Print();
cout << endl;
String2.Print();
cout << endl;
String2.Copy(String1);
String1.Print();
cout << endl;
String2.Print();
cout << endl;
输出:
Hello World
This is a test
is a test
This is a test
它应该是:
Hello World
This is a test
Hello World
Hello World
请给我解释一下我究竟做错了什么?
这里是我的整个.cpp文件:
MyString::MyString()
{
char temp[] = "Hello World";
int counter(0);
while(temp[counter] != '\0') {
counter++;
}
Size = counter;
String = new char [Size];
for(int i=0; i < Size; i++)
String[i] = temp[i];
}
MyString::MyString(char *message)
{
int counter(0);
while(message[counter] != '\0') {
counter++;
}
Size = counter;
String = new char [Size];
for(int i=0; i < Size; i++)
String[i] = message[i];
}
MyString::~MyString()
{
delete [] String;
}
int MyString::Length()
{
int counter(0);
while(String[counter] != '\0')
{
counter ++;
}
return (counter);
}
void MyString:: Set(int index, char b)
{
if(String[index] == '\0')
{
exit(0);
}
else
{
String[index] = b;
}
}
void MyString::Copy(MyString& one)
{
one = String;
}
char MyString:: Get(int i)
{
if(String[i] == '\0')
{
exit(1);
}
else
{
return String[i];
}
}
void MyString::Print()
{
for(int i=0; i < Size; i++)
cout << String[i];
cout << endl;
}
'void MyString :: Copy'是一个成员函数,而不是一个拷贝构造函数。一个拷贝构造函数会有一个签名'MyString :: MyString(const MyString&other)',根本没有返回类型,甚至没有'void'。 – dasblinkenlight 2012-04-21 01:21:12
这里是我的教授指示:MyString对象应该有一个Copy(...)方法,可以将一个对象复制到另一个对象中....我是否弄糊涂了? – user964141 2012-04-21 01:25:55
@ user964141是的,复制方法与复制构造函数不同。 – bames53 2012-04-21 01:28:52