为什么这里需要构造函数和赋值操作符
why do I need both constructor and assignment operator here?
当省略其中一个时,我的代码无法编译。我认为在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";
首先用"Hello world"
创建一个临时AString
,然后将first
分配给它。
所以你需要AString::AString( const char *s )
,但它不是复制构造函数
相关文章:
- C++ 基本 CTOR 说明 - 为什么不调用赋值/复制构造函数
- 错误的数组初始化与赋值副本构造函数初始化
- 赋值复制构造函数
- 复制构造函数,赋值操作符重载
- 通过调用Move赋值操作符实现Move构造函数
- 单参数构造函数和赋值操作符
- 如何从复制赋值操作符调用复制构造函数
- c++复制构造函数,重载赋值操作符,方法get()
- 类赋值操作符和复制构造函数
- 影响正确性的move构造函数/赋值操作符示例
- 如果没有定义Move语义(Move构造函数和Move赋值操作符),编译器是否默认优化
- 即使类没有定义构造函数,也不能在类上调用c++默认的move赋值操作符
- 复制构造函数和赋值操作符都被调用
- 与智能指针相关的c++移动语义与复制构造函数和赋值操作符
- 为什么不是只有一个?复制构造函数和赋值操作符
- c++析构函数、复制构造函数和赋值操作符实践考试
- 为什么这里需要构造函数和赋值操作符
- 赋值给构造函数中的常量变量
- 成员初始化列表vs赋值/复制构造函数(在boost deadline_timer中)
- 将传递的对象赋值给构造函数中的成员对象