Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/156.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 清除具有已删除赋值运算符的成员的类实例_C++ - Fatal编程技术网

C++ 清除具有已删除赋值运算符的成员的类实例

C++ 清除具有已删除赋值运算符的成员的类实例,c++,C++,我想使用赋值运算符清除/重新实例化一个类的实例,但该类中的某些成员已删除了其赋值运算符。因此,当我尝试将其分配给新实例时,它会保留其旧值 下面是一个例子: #include <cstdio> class C { C operator= (const C&) = delete; }; class B { public: int x = 0; C c; B& operator=(const B& other) {

我想使用赋值运算符清除/重新实例化一个类的实例,但该类中的某些成员已删除了其赋值运算符。因此,当我尝试将其分配给新实例时,它会保留其旧值

下面是一个例子:

#include <cstdio>
class C
{
    C operator= (const C&) = delete;
};

class B
{
public:
    int x = 0;
    C c;
    B& operator=(const B& other)
    {
        return B();
    }
};
int main()
{
    B b;
    b.x = 5;
    b = B();
    printf("%i\n", b.x); // prints 5, should print 0
    return 0;
}
在不编写清除其所有成员的方法的情况下,是否有一些简单的解决方法?为什么会发生这种情况

为什么会发生这种情况

运算符=的当前实现是fubar

B& operator=(B const &other)
{
    x = other.x;
    return *this;
}
不过,在做任何事情之前,您还应该测试自我分配,因为复制成员可能会非常昂贵:

B& operator=(B const &other)
{
    if(this != &other)
        x = other.x;

    return *this;
}

B&operator=constb&other{return*this;}给出了相同的结果result@rbwxgf如果该语句对问题中显示的函数main为真,则编译器已损坏。@rbwxgf编辑问题并显示整个代码。@rbwxgf-新版本的赋值运算符未赋值tox,所以x的值不变。这就是这个答案的要点:原来的版本也没有。仔细阅读答案中的代码,并将其与你的代码进行比较。我是个白痴。是的,我有点希望避免为所有成员写作业,但是没有办法。甚至不知道我是怎么想的;是一个错误,应该无法编译