【问题标题】:why do I need both constructor and assignment operator here?为什么我在这里需要构造函数和赋值运算符?
【发布时间】: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


【解决方案1】:

second = first = "Hello world"; 首先用"Hello world" 创建一个临时AString,然后将first 分配给它。

所以你需要AString::AString( const char *s ),但它不是复制构造函数。

【讨论】:

  • [expr.ass]/1 "赋值运算符 (=) 和复合赋值运算符都从右到左分组。"
  • 是的,确切地说,我已经更新了问题,我暂时忽略了。不要问怎么做。
  • 如果您按照通常的建议将采用单个 arg 的构造函数标记为 explicit,则此代码会给您预期的错误。
猜你喜欢
  • 2023-03-13
  • 2011-05-21
  • 2011-07-26
  • 1970-01-01
  • 2020-10-31
  • 2012-07-27
  • 2022-01-03
  • 2011-07-19
  • 1970-01-01
相关资源
最近更新 更多