J
junyangzou
This is an excerpt from "Effective C++" item 03. I add some code to actually make it runnable. And here is the question: I tried to change the static_cast<const TextBook&> to static_cast<const TextBook>, and it runs good. So is there any difference between the two statement.
1 #include <iostream>
2 #include <string>
3
4 using namespace std;
5
6 class TextBook {
7 public:
8 TextBook( std::string name = "" )
9 :text(name){}
10 const char& operator[] ( std::size_t position ) const {
11 return text[position];
12 }
13
14 char& operator[] ( std::size_t position ) {
15 return const_cast<char&>(
16 static_cast<const TextBook&>(*this)[position]
17 );
18 }
19 private:
20 std::string text;
21 };
22
23 int main() {
24 TextBook book("Effective C++");
25 const TextBook book2(book);
26
27 //cout << book[0] << " " << book2[0] << endl;
28 book[0] = 'D';
29 cout << book[0] << endl;
30 return 0;
31 }
1 #include <iostream>
2 #include <string>
3
4 using namespace std;
5
6 class TextBook {
7 public:
8 TextBook( std::string name = "" )
9 :text(name){}
10 const char& operator[] ( std::size_t position ) const {
11 return text[position];
12 }
13
14 char& operator[] ( std::size_t position ) {
15 return const_cast<char&>(
16 static_cast<const TextBook&>(*this)[position]
17 );
18 }
19 private:
20 std::string text;
21 };
22
23 int main() {
24 TextBook book("Effective C++");
25 const TextBook book2(book);
26
27 //cout << book[0] << " " << book2[0] << endl;
28 book[0] = 'D';
29 cout << book[0] << endl;
30 return 0;
31 }