Operator Overloading part 2(Chapter 12 of Thinking in C++)
2010-11-27 14:20
295 查看
1 #include <iostream>
2 #include <sstream>
3 #include <cstring>
4 using namespace std;
5
6 class IntArray
7 {
8 enum { sz = 5 };
9 int i[sz];
public:
IntArray()
{
memset(i, 0, sz * sizeof(*i));
}
int& operator[](int x)
{
return i[x];
}
friend ostream& operator<<(ostream& os, const IntArray& ia);
friend istream& operator>>(istream& is, IntArray& ia);
};
ostream& operator<<(ostream& os, const IntArray& ia)
{
for(int j=0; j<ia.sz; j++)
{
os << ia.i[j];
if(j != ia.sz - 1)
{
os << ", ";
}
}
os << endl;
return os;
}
istream& operator>>(istream& is, IntArray& ia)
{
for(int j=0; j<ia.sz; j++)
{
is >> ia.i[j];
}
return is;
}
int main()
{
stringstream input("47 34 56 92 103");
IntArray I;
input >> I;
I[4] = -1;
cout << I;
}
2 #include <sstream>
3 #include <cstring>
4 using namespace std;
5
6 class IntArray
7 {
8 enum { sz = 5 };
9 int i[sz];
public:
IntArray()
{
memset(i, 0, sz * sizeof(*i));
}
int& operator[](int x)
{
return i[x];
}
friend ostream& operator<<(ostream& os, const IntArray& ia);
friend istream& operator>>(istream& is, IntArray& ia);
};
ostream& operator<<(ostream& os, const IntArray& ia)
{
for(int j=0; j<ia.sz; j++)
{
os << ia.i[j];
if(j != ia.sz - 1)
{
os << ", ";
}
}
os << endl;
return os;
}
istream& operator>>(istream& is, IntArray& ia)
{
for(int j=0; j<ia.sz; j++)
{
is >> ia.i[j];
}
return is;
}
int main()
{
stringstream input("47 34 56 92 103");
IntArray I;
input >> I;
I[4] = -1;
cout << I;
}
相关文章推荐
- Operator Overloading part 1(Chapter 12 of Thinking in C++)
- Operator Overloading part 3(Chapter 12 of Thinking in C++)
- Function Overloading & Default Arguments(Chapter 7 of Thinking in C++)
- Name Control(Chapter 10 of Thinking in C++)
- References & the Copy-Constructor(Chapter 11 of Thinking in C++)
- Dynamic Object Creation(Chapter 13 of Thinking in C++)
- Question 12: In C++, which of the following is the best declaration for an overloaded operator[] to allow read-only access (and
- Templates in depth(Chapter 3 of Thinking in C++ Vol 2)
- Inheritance & Composition(Chapter 14 of Thinking in C++)
- Data Abstraction(Chapter 4 of Thinking in C++)
- Iostreams part1(Chapter 2 of Thinking in C++ Vol 2)
- STL Containers & Iterators part2(Chapter 4 of Thinking in C++ Vol 2)
- return value of operator overloading in C++
- Polymorphism & Virtual Functions(Chapter 15 of Thinking in C++)
- Iostreams part2(Chapter 2 of Thinking in C++ Vol 2)
- The Preprocessor(Chapter 12 of Programming in Objective-C 2.0)
- The C in C++(Chapter 3 of Thinking in C++)
- Inline Functions(Chapter 9 of Thinking in C++)
- Constants(Chapter 8 of Thinking in C++)
- STL Containers & Iterators part1(Chapter 4 of Thinking in C++ Vol 2)