【发布时间】:2013-05-08 21:08:39
【问题描述】:
当省略其中之一时,我的代码无法编译。我认为main() 中只需要复制赋值运算符。哪里还需要构造函数?
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
class AString{
public:
AString() { buf = 0; length = 0; }
AString( const char*);
void display() const {std::cout << buf << endl;}
~AString() {delete buf;}
AString & operator=(const AString &other)
{
if (&other == this) return *this;
length = other.length;
delete buf;
buf = new char[length+1];
strcpy(buf, other.buf);
return *this;
}
private:
int length;
char* buf;
};
AString::AString( const char *s )
{
length = strlen(s);
buf = new char[length + 1];
strcpy(buf,s);
}
int main(void)
{
AString first, second;
second = first = "Hello world"; // why construction here? OK, now I know : p
first.display();
second.display();
return 0;
}
是因为这里
second = first = "Hello world";
第一个临时由AString::AString( const char *s )创建?
【问题讨论】:
-
这是一个赋值:
second = first /* = "Hello world" */;你可以只使用复制构造函数:AString first("Hello world"); AString second(first); -
您的代码在 g++ 4.7 和 4.8 上编译良好...
-
复制和分配...
-
请注意The Rule of Three(在 C++11 中是五法则,因为我们还有移动运算符和移动赋值运算符。)
-
您在上面的代码中没有复制构造函数。您只有一个赋值运算符和一个恰好采用 const char* 的构造函数
标签: c++ copy-constructor assignment-operator