Wednesday, August 14, 2013

Newsgroup: comp.lang.c++

Subject: Difference between static_cast<const A>(*this) and static_cast<const A&>(*this)

From: junyangzou <zoujyjs@...>

Date: Tue, 13 Aug 2013 07:19:32 -0700 (PDT)



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 }







via Usenet Forums - Usenet Search,Free Usenet - comp.lang.c++ http://www.pocketbinaries.com/usenet-forums/showthread.php?64717-Difference-between-static_cast(*this)-and-static_cast(*this)&goto=newpost

View all the progranning help forums at:

http://www.pocketbinaries.com/usenet-forums/forumdisplay.php?128-Coding-forums

No comments:

Post a Comment