私はオブジェクト指向プログラムでこのコピーコンストラクタを実行するのに助けが必要です。結果は、文字列1:Hello World
を文字列2にコピーすることです。This is a test
。.Copyを使ってコピーコンストラクタを実行する最善の方法は?
String1.Print();
cout << endl;
String2.Print();
cout << endl;
String2.Copy(String1);
String1.Print();
cout << endl;
String2.Print();
cout << endl;
:私の
main.cpp
ファイルで
void MyString::Copy(MyString& one)
{
one = String;
}
:私の.cpp
ファイルで
void Copy(MyString& one);
:私の.h
ファイルで
出力:
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
ここに私の教授の指示があります:MyStringオブジェクトには、あるオブジェクトを別のオブジェクトにコピーするCopy(...)メソッドが必要です。 – user964141
@ user964141はい、コピーメソッドはコピーコンストラクタと同じものではありません。 – bames53