【发布时间】:2012-04-21 01:17:59
【问题描述】:
我需要帮助在我的面向对象程序中执行这个复制构造函数。结果应该是将字符串 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;
}
【问题讨论】:
-
void MyString::Copy是成员函数,而不是复制构造函数。复制构造函数将具有签名MyString::MyString(const MyString& other),并且根本没有返回类型,甚至没有void。 -
这是我教授给我的指令:MyString 对象应该有一个 Copy(...) 方法,可以将一个对象复制到另一个对象中....我把 2 弄糊涂了吗?
-
@user964141 是的,复制方法与复制构造函数不同。
-
不,说明是正确的:
Copy(...)可以称为 方法(这在面向对象的其他世界中是这样称呼的,但在 C++ 中它被称为成员函数)。但是Copy不是构造函数。 -
你的代码有很多问题,你应该学会使用标准库容器和算法。计算 C 字符串的长度可以像
strlen( ptr )一样简单,您应该更频繁地使用const,例如Set函数不会修改对象。关于此函数的实现检查您是否不覆盖空终止符,但它不检查索引是否有效(即在[0..Size)范围内),要么提供完整检查,要么根本不检查。Length重新计算Size的值...
标签: c++ string object copy-constructor