// casts.cpp -- demonstrate uses of the new casts #include #include using namespace std; //----< test2 does not guarantee s will not be changed >------- int test2(char *s) { return strlen(s); } //----< test1 guarantees s will remain unchanged >------------- void test1(const char *s) { // this call will not succeed without the const_cast // because the compiler does not know that test2 will // not change the state of s int len = test2(const_cast(s)); } class Try { public: test0(char *s); test1(const char *s); test2(char *s) const; }; Try::test0(char *s) { cout << " Try::test0(char *s) succeeded\n"; } Try::test1(const char *s) { cout << " Try::test1(char *s) succeeded\n"; } Try::test2(char *s) const { cout << " Try::test2(char *s) const succeeded\n"; } // //----< test stub >-------------------------------------------- void main() { char *myString = "This is a string."; test1(myString); char *ncs = "string s1"; const char *cs = "string s2"; Try nct; const Try ct; // all of the const_casts below are necessary for the // affected statements to compile nct.test0(ncs); nct.test0(const_cast(cs)); nct.test1(ncs); nct.test1(cs); nct.test2(ncs); nct.test2(const_cast(cs)); // can't do this: const_cast(ct).test0(ncs); const_cast(&ct)->test0(ncs); const_cast(&ct)->test0(const_cast(cs)); const_cast(&ct)->test1(ncs); const_cast(&ct)->test1(cs); ct.test2(ncs); ct.test2(const_cast(cs)); }