【问题标题】:c++ object construction using operator=使用 operator= 的 c++ 对象构造
【发布时间】:2015-05-20 07:48:05
【问题描述】:

我是这样维护三人法则的--

// actual constructor
stuff::stuff(const string &s)
{
    this->s_val = s[0];
    this->e_val = s[s.length() - 1];
}

// copy constructor
stuff::stuff(const stuff &other)
{
    this->s_val = other.s_val ;
    this->e_val = other.e_val ;
}

// assignment
stuff& stuff::operator=(const stuff &other)
{
    stuff temp(other);
    *this = move(temp); 
    return *this;
}

现在我可以这样打电话了--

stuff s1("abc");
stuff s2(s1);
stuff s3 = s2 ; // etc ...

现在我正在尝试实现一个将使用 operator= 的函数,以便我可以像这样调用 --

stuff s;
s = "bcd" ;

我是这样写的——

stuff& stuff::operator=(const string &s)
{
    stuff temp(s);
    *this = move(temp);
    return *this;
}

但它给了我段错误。此外,如果想打电话我该怎么办

stuff s = "bcd" ?

我该怎么做?

【问题讨论】:

  • *this = move(temp); 正在调用您尝试定义的赋值运算符。
  • 我明白了,它是在进行递归调用吗?
  • 是的,确实如此。
  • 等一下,但我的operator=() 有一个string 参数,而不是stuff,那么为什么它不在stuff& stuff::operator=(const stuff &other) 中进行递归调用?
  • 你的另一个operator=。带有递归调用的那个(除非你有移动赋值,但你没有展示出来。)无论如何,你真的需要实现特殊的成员函数吗?如果是这样,请显示足够的代码来证明您这样做。

标签: c++ c++11 constructor operator-overloading


【解决方案1】:

你的赋值运算符和复制构造函数应该看起来一样:

stuff& stuff::operator=(const stuff &other)
{
    this->s_val = other.s_val ;
    this->e_val = other.e_val ;
    return *this;
}

你不能用另一个 = 运算符定义你的 = 运算符。 请记住,std::move 没有做任何特殊的魔法,它只是将一个变量变成可以使用移动语义咳嗽的东西。您仍然需要将您的函数定义为首先处理 r-value-reference 的函数,而您没有(您没有任何移动赋值运算符)。

在你接受字符串的= 运算符中,你可以使用常规的:

stuff& stuff::operator=(const string &s)
{
    *this = stuff(s);
    return *this;
}

还有一些建议: 你的this-> 是多余的。编译器知道您引用的变量是this 的一部分。 还有,行:

this->s_val = s[0];
this->e_val = s[s.length() - 1];

可以更优雅地写成:

s_val = s.first();
e_val = s.back();

顺便说一句。复制 ctor.、assignemt 运算符和析构函数也是多余的。 三(或五,如 C++11)规则说 *IF* you implement any of the copy ctor. assigment operator or the destructor - you need to implement them all. 问题是,您是否应该首先实施其中任何一个?您在这里没有任何动态分配,没有浅拷贝,也没有什么特别需要特殊成员函数(复制ctor等)。 您不妨删除全部三个,这将是您的示例中最好的情况。

【讨论】:

  • 谢谢,过了一会儿我想通了,但我仍然无法以像stuff s4 = "bcd" 一样调用的方式重载它,我试图将参数更改为const char *c但仍然在说error: conversion from ‘const char [4]’ to non-scalar type ‘stuff’ requested 有什么想法吗?
  • 你用的是什么编译器?
  • g++ 4.8.2 支持c++11
  • 它应该可以工作,就像这里:coliru.stacked-crooked.com/a/4d29a34a748cb5cb
  • 是的,当我说A a; a = "abc"; 时它可以工作,但当我说A a = "abc"; 时它不起作用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-11
  • 2011-02-20
  • 1970-01-01
  • 2017-02-22
相关资源
最近更新 更多