I'm designing a little mathematical library. I have classes that represents classes of function, e.g. polynomial. When they're instantiated, the parameters needed (a1, a2, a3) are provided so the object actually represent a specific polynomial (a1*x^2 + a2*x + a3).

Then I want to provide the functionality of evaluating the function at a certain point (x=3, y=?). I've read this wiki and chapter 12 of Thinking in C++, Vol. 1 by Bruce Eckel. Both of them says that I should decide whether to overload or not based on the "meaning" of the operator. I'm not an experienced C++ programmer, but to my knowledge, if I have a class representing a function and I use obj(x) what I expect is the value y the function takes at that x.

The doubts arises with dimensions: I have to represent vector functions too (http://en.wikipedia.org/wiki/Vector_function), like a1*x1 + a2*x2, and I will have signature like this: operator()(real x1, real x2). My problem is with the return type. If y1 = a1*x1 + a2*x2 is a vector (both mathematically and in C++), should I return y1 by value or by reference? And should I provide also a const version?

PS it's my first question here on Stackoverflow.com so please tell me if something of the question is wrong (title, tags, question itself :P) and I'll gladly correct it.

有帮助吗?

解决方案

'should I return y1 by value or by reference?' By value undoubtedly, there's no good way to return a reference to a newly created object. If the cost of copying your objects is an issue then you should look to some kind of smart pointer technique to provide fast copying.

'And should I provide also a const version?' From what you have said you should only provide a const version.

其他提示

You only return something by reference if it is stored permanently somewhere else. Since your return value is temporary, it should be returned by value.

Since you are not changing anything of the function, the method should be const.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top