如何重载=运算符 [英] How to Overload = operator
问题描述
大家好,
我想在VC ++中为=运算符编写一个运算符重载函数.我该怎么写.谁能告诉我vc ++中运算符重载的语法.我需要紧急帮助..请帮助我..
hi all,
i want to write an operator overloaded function for = operator in VC++. how can i write. can anybody please tell me the syntax of operator overloading in vc++. i need an urgent help..please help me..
推荐答案
在这里,您去了.. http://www.umsl.edu/~subramaniana/overload4.html [ ^ ]
Hi,
Here you go..http://www.umsl.edu/~subramaniana/overload4.html[^]
Google搜索结果->
(未编译)示例,其中包含一个包含整数数组的类:
(Uncompiled) example with a class containing an array of ints:
class A
{
int *_ptr;
int _count;
A& operator=(const A& rhs)
{
if (this != &rhs)
{
// Clean-up of this
delete _ptr;
// Assinment here
_count = rhs._count;
_ptr = new int[_count];
std::copy(rhs._ptr, &rhs.ptr[_count], _ptr);
}
return *this;
}
};
您返回非const引用的事实允许使用一些尴尬的方法:
The fact that you return a non-const reference allows for a bit awkward usage:
A a1, a2, a3;
(a1 = a2) = a3;
恕我直言,返回const引用将是一个更好的选择,即使它不符合内置类型.
请注意在这种情况下如何需要避免自我分配.如果我们不检查自我分配,该方法的清理部分将在我们有机会复制数据之前销毁数据.
IMHO returning a const reference would be a better choice, even though it would not conform to the built in types.
Note how it''s needed to avoid self assignment in this case. If we did not check for self-assignment, the clean-up part of the method would destroy the data before we had a chance to copy it.
这篇关于如何重载=运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!