使用重载赋值操作符
Using overloaded assignment operator
我有一个具有非默认构造函数和重载赋值操作符的template<> class A
:
template<typename T>
class A
{
public:
A(T x);
A(A<T> &parent);
A<T> & operator=(A<T> &rhs);
};
和class B
,其中A
是成员,它有自己的重载赋值操作符和a
class B
{
public:
B();
B& operator=(B &rhs);
A<int> get_A();
protected:
A<int> *member;
};
我已经定义了赋值操作符和A
getter方法如下:
B& B::operator=(B &rhs)
{
*member = rhs.get_A();
return *this;
}
A<int> B::get_A()
{
return *member;
}
赋值操作符在这种情况下不起作用。我遗漏了什么吗?我得到以下错误:
B.cpp(92): error: no operator "=" matches these operands
operand types are: A<int> = A<int>
我也试过
B& B::operator=(B &rhs)
{
A<int> temp(rhs.get_A());
*member = temp;
return *this;
}
在这种情况下,我得到:
B.cpp(92): error: no instance of constructor "A<T>::A [with T=int]" matches the argument list
argument types are: (A<int>)
A<int> temp(rhs.get_A());
1
关于A<T> & operator=(A<T> &rhs);
最好是
A<T>& operator=(A<T> const& rhs);
2 关于
B& B::operator=(B &rhs)
{
*member = B.get_A();
return *this;
}
最好是
B& B::operator=(B const& rhs)
{
*member = rhs.get_A();
return *this;
}
3
关于 B() : member(4);
不能编译的很难说它应该是什么,因为member
被声明为指针,而提供的值是一个不兼容的整数。
4 关于
A<int> get_A();
最好是
A<int> get_A() const;
可以在const
对象上调用。
5
关于
注释” A稍微复杂一些,包含一个链表。每次复制A的对象时,都必须更新链表
对象每次复制时都必须更新,这听起来确实有点可疑。旧的std::auto_ptr
类几乎就是这样,它通过一个涉及特殊代理引用类的黑客来实现这种效果。可能你的对象不是真正可复制的,而只是可移动的,在这种情况下,无论操作是什么,都不要使用复制赋值操作符,而是使用普通的命名成员函数。
相关文章:
- c++中的重载赋值操作符
- 复制构造函数,赋值操作符重载
- c++复制构造函数,重载赋值操作符,方法get()
- 赋值操作符重载
- 当类是子类时重载赋值操作符
- 模板类的重载赋值操作符
- 使用重载赋值操作符
- 类和向量的重载赋值操作符
- c++模板赋值操作符重载——赋基本类型给对象
- 在可强制转换为另一个模板类型的类模板中重载赋值操作符
- 无法重载赋值操作符
- 赋值操作符重载:错误处理场景
- 使用重载复合赋值操作符时的运行时错误
- 赋值操作符重载未被调用
- c++ const重载赋值操作符机制
- 在子类类中重载基类赋值操作符会导致二义性赋值错误
- 创建了自己的字符串类——重载赋值操作符和析构函数的错误
- 子类,赋值操作符重载
- 算术和赋值操作符重载-返回值,范围,组合表达式
- 模板赋值操作符重载之谜