简体   繁体   中英

C++ operator overloading for myClass(x,y,z) = value

In C++, how should I overload the function call operator in order that an instance of my class can take in such an expression: myClass(x,y,z) = value ?

I have a template class Array3D, which is used as a wrapper for a 1D array. I want to set a specif value at a certain index in this array. Till now I used to do it with a regular function like so:
array.setValueAt(int x, int y, int z, int value)
but now I wanted to overload the function call operator and use it instead. So something like that: array(x, y, z) = value

You want the function call operator, operator() :

struct Foo
{
    int & operator()(int, int, int) { return x; }
    int x;
};

You should make it return an lvalue (or otherwise something which overloads assignment) in order for your assignment example to work.

Usage:

Foo a;
a(1, 2, 3) = 10;

assert(a.x == 10);

If your class holds values of some type ValueType , you can return a reference to it:

ValueType & operator () (int x, int y, int z);

assuming you are indexing with int . For completeness, you might find it convenient to add:

const ValueType & operator () (int x, int y, int z) const;

for const access to the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM