簡単な例として、次のクラスを考えてみましょう。
#include <iostream>
#include <string>
using namespace std;
class point {
public:
int _x{ 0 };
int _y{ 0 };
point() {}
point(int x, int y) : _x{ x }, _y{ y } {}
operator string() const
{ return '[' + to_string(_x) + ',' + to_string(_y) + ']'; }
friend ostream& operator<<(ostream& os, const point& p) {
// Which one? Why?
os << static_cast<string>(p); // Option 1
os << p.operator string(); // Option 2
return os;
}
};
変換演算子を直接呼び出す必要がありますか、それとも単に呼び出しstatic_cast
てそれで処理を任せるべきでしょうか?
これら 2 つの行はほとんど同じことを行います (つまり、変換演算子を呼び出します)。私が知る限り、これらの動作に実際の違いはありません。したがって、ここでの本当の問題は、それが本当かどうかです。これらは私には同じように見えますが、理解できない微妙な違いがまだある可能性があります.
では、構文が異なるという事実以外に、これらのアプローチ (この例には当てはまらない可能性があるものも含む) の間に実際的な違いはありますか? どちらを優先する必要がありますか?その理由は?