有人可以解释一下编译器如何调用运算符转换吗:
operator ELEMENT()const {
return pArray->arr[index];
}
来自 main 中的第 6 行:
(*ptr3)[0] = a1[0] + a2[1];
如何使用 + 运算符添加两个 ELEMENT 对象? ELEMENT 类中没有 + 运算符重载。
谢谢, 利隆
#include <iostream>
using namespace std;
template<class ELEMENT> class Array
{
class Element
{
Array<ELEMENT>* pArray;
int index;
public:
Element(Array<ELEMENT>* p, int i)
: pArray(p), index(i) {}
const Element& operator=(const ELEMENT& e) {
pArray->set(index, e); // call copy-on-write
return *this;
}
operator ELEMENT()const {
return pArray->arr[index];
}
};
friend class Element;
ELEMENT* arr;
int size;
int* ref_counter;
void attach(const Array& a) {
arr = a.arr; size = a.size;
ref_counter = a.ref_counter;
++(*ref_counter);
}
void detach() {
if(--(*ref_counter) == 0) {
delete []arr;
delete ref_counter;
}
}
void set(int index, const ELEMENT& e) {
if(*ref_counter > 1) { // need copy-on-write!
Array temp = clone();
detach();
attach(temp);
}
arr[index] = e;
}
public:
explicit Array(int);
Array<ELEMENT> clone()const;
Array(const Array<ELEMENT>& a){attach(a);}
~Array(){detach();}
const Array& operator=(const Array<ELEMENT>& a) {
detach(); attach(a); return *this;
}
Element operator[](int index) {
return Element(this, index);
}
const ELEMENT& operator[](int index)const {
return arr[index];
}
};
template<class ELEMENT>
Array<ELEMENT>::Array(int size1)
: size(size1), ref_counter(new int(1))
{
arr = new ELEMENT[size];
}
template<class ELEMENT>
Array<ELEMENT> Array<ELEMENT>::clone()const {
Array temp(size);
for(int i=0; i<size; ++i) {
temp.arr[i] = arr[i];
}
return temp;
}
int main()
{
Array<int> a1(1), a2(2);
Array<int>* ptr3 = new Array<int>(3);
a2[0] = 1;
a2[1] = 2;
a1 = a2;
(*ptr3)[0] = a1[0] + a2[1];
(*ptr3)[1] = a1[1] + a2[0];
cout << (*ptr3)[0] << ", " << (*ptr3)[1] << endl;
delete ptr3;
return 1;
}
最佳答案
How adding two ELEMENT object with + operator even allowed? There is no + operator overloading in ELEMENT class.
ELEMENT
不是一个类,它是一个类型参数。在您的示例中,为该参数指定的类型是 int
。显然int
确实有一个+
运算符,这样就可以正常工作了。如果您尝试创建 Array<SomeType>
哪里SomeType
没有+
运算符,您会收到错误。
有一个Element
类,并且该类确实没有 +
运算符,但该类可以隐式转换为 ELEMENT
(即本例中的int
),所以当您申请+
时到 Element
的对象编译器添加对该转换运算符的调用和 +
应用于结果。
关于c++ - 编译器如何调用运算符转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21811730/