gpt4 book ai didi

c++ - 具有多重继承的复制赋值运算符

转载 作者:太空狗 更新时间:2023-10-29 23:43:34 25 4
gpt4 key购买 nike

我下面的复制构造函数工作正常,但我不明白我的复制赋值运算符有什么问题。

#include <iostream>

template <typename... Ts> class foo;

template <typename Last>
class foo<Last> {
Last last;
public:
foo (Last r) : last(r) { }
foo() = default;
foo (const foo& other) : last(other.last) { }

foo& operator= (const foo& other) {
last = other.last;
return *this;
}
};

template <typename First, typename... Rest>
class foo<First, Rest...> : public foo<Rest...> {
First first;
public:
foo (First f, Rest... rest) : foo<Rest...>(rest...), first(f) { }
foo() = default;
foo (const foo& other) : foo<Rest...>(other), first(other.first) { std::cout << "[Copy constructor called]\n"; }

foo& operator= (const foo& other) { // Copy assignment operator
if (&other == this)
return *this;
first = other.first;
return foo<Rest...>::operator= (other);
}
};

int main() {
const foo<int, char, bool> a(4, 'c', true);
foo<int, char, bool> b = a; // Copy constructor works fine.
foo<int, char, bool> c;
// c = a; // Won't compile.
}

错误信息:

error: invalid initialization of reference of type 'foo<int, char, bool>&' from expression of type 'foo<char, bool>'
return foo<Rest...>::operator= (other);
^

有人能指出这里的问题吗?

最佳答案

您的返回声明

return foo<Rest...>::operator= (other);

返回 foo<Rest...> (这是引用类型 operator= 定义的)。但它是由一个应该返回 foo<First, Rest...>& 的运算符(operator)执行的.

本质上,您返回一个 Base其中一个 Derived&预计引用。引用根本不会绑定(bind)。

幸运的是修复很简单:不要返回 foo<Rest...>::operator= 的结果, 返回 *this相反。

foo& operator= (const foo& other) {  // Copy assignment operator
if (&other == this)
return *this;
first = other.first;
foo<Rest...>::operator= (other);
return *this;
}

关于c++ - 具有多重继承的复制赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47488389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com