操作员过载"equal to"
Operator overloading "equal to"
我想为重载C++中等于"="的运算符
class Array
{
int *p;
int len;
};
定义了所有函数/构造函数等。
我的问题:有人能给我运算符重载函数的原型吗?假设:
Array a,b;
b=a;
"a"answers"b"中的哪一个将隐式传递,哪一个显式传递?
提前谢谢。
原型是Array& operator=(const Array& that)
。
在实现这一点时,请记住"三条规则",并充分利用复制和交换习惯用法。
您正在寻找赋值运算符=(不等于,这是operator==
,通常用作相等比较)
class Array
{
int *p;
int len;
public:
// Assignment operator, remember that there's an implicit 'this' parameter
Array& operator=(const Array& array)
{
// Do whatever you want
std::cout << "assignment called";
return *this;
}
};
int main(void) {
Array a, b;
a = b;
}
请记住,由于您编写了"所有函数/构造函数等都已定义",因此您应该注意您的类需要做什么,并可能按照三规则实现析构函数(和/或查看其在C++11中的变体,可能是相关的,因为没有发布其他代码)。
可能有不止一种方法,但这里有一个选项。
公共功能:
Array::Array(const Array& array)
{
Allocate(0);
*this = array;
}
Array::~Array()
{
Deallocate();
}
const Array& Array::operator=(const Array& array)
{
if (this == &array)
return *this;
Deallocate();
Allocate(array.len);
for (int i=0; i<len; i++)
p[i] = array.p[i];
return *this;
}
非公共功能:
void Array::Allocate(int size)
{
len = size;
if (len > 0)
p = new int[len];
}
void Array::Deallocate()
{
if (len > 0)
delete[] p;
len = 0;
}
当然,您可以始终使用vector<int>
来代替。。。
相关文章:
- "error: no matching function for call to"构造函数错误
- 调用专用模板时出错"no matching function for call to [...]"
- C++ Singleton - Prevent ::instance() to variable
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- Visual Studio Code "undefined reference to `WinMain@16'"
- 使用 GCC 卸载的 OpenMP 卸载失败,并出现"Ptx assembly aborted due to errors"
- 如何解决"invalid conversion from 'char' to 'const char*'"
- 使用 MATLAB 编码器生成C++代码:编译错误"undefined reference to `rgb2gray_tbb_real64'"
- 尝试链接我的着色器时,我收到错误代码"error c5145 must write to gl_position"
- Python str to C++ to Python str
- 为什么创建友元类的实例会导致"undefined reference to"错误?
- System.InvalidCastException - SQL to C++ - safe_cast<float>
- 如何使用"equal to"以外的评估编写开关语句
- 使用'equal to'符号初始化期间的内存
- 在 C 族中,在一个循环中,为什么"less than or equal to"比"less than"符号更受欢迎?
- 我怎样才能写得"if not greater than or equal to some value"雄辩?
- (false - NOT (0)) is equal to 1?
- 操作员过载"equal to"
- if-else 语句中的"equal to"运算符与"not equal to"运算符
- SignedXML class equal to visual C++?