J
Jason Heyes
E. Robert Tisdale said:Greg said:That's a very good rule of thumb, but if I'm understanding you,
forcing an initialization can often be awkward.
Not very often
but I'll give an example where it is awkward -- containers:
int a[n];
for (int j = 0; j < n; ++j)
cin >> a[n];
Unless they are small, const containers can be awkward to initialize:
const int a[] = {0, 1, 2, 3};
Well, you get the idea. You can do this:
class wrapper {
private:
int a[n];
public:
const
int& operator[](int j) const { return a[j]; }
int& operator[](int j) { return a[j]; }
wrapper(std::istream& is) {
for (int j = 0; j < n; ++j)
is >> a[n];
}
};
then this:
const wrapper a(cin);
Of course, this can cause a problem,
if the constructor encounters an exception while reading from cin.
Is this awkward? Problematic?
I suspect that you would say yes.
To get around this you can write
std::istream &operator>>(std::istream &is, wrapper *&p)
{
int a[n];
for (int j=0; j < n; j++)
{
if (!(is >> a[j]))
return is;
}
p = new wrapper(a);
return is;
}
then
wrapper *p;
if (!(cin >> p))
// error
wrapper a = *p;
delete p;
OR you can use std::vector instead of arrays!