我需要帮助在我的面向对象程序中执行这个复制构造函数。结果应该是将字符串 1: 复制Hello World
到字符串 2:This is a test
中。
在我的.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;
}