九天雁翎的博客
如果你想在软件业获得成功,就使用你知道的最强大的语言,用它解决你知道的最难的问题,并且等待竞争对手的经理做出自甘平庸的选择。 -- Paul Graham

和实现有关的相同字符串存储方式检验的思考及c-string字符串

/*Copyright (c) 2007,九天雁翎

* All rights reserved.

* 和实现有关的相同字符串存储方式检验的思考

* 完成日期:2007年7月7日*/

#include "stdafx.h"

#include <iostream>

using namespace std;

int main()
{
    char *p1 = "Hello the world!";
    char *p2 = "Hello the world!";
    if(p1 == p2)
    {
        //ok,We could know it is the same as Bjarne Stroustrup said in VC++2005
        cout << "The same."<<endl;          
    }
    else
    {
        cout << "Not the same."<<endl;
    }
    //But look at this
    cout << &p1 <<'/t' <<&p2 <<endl;
    //the adress output is not the same!
    //Do you want to output it use p1 and p2?
    //Let try;
    cout << p1 <<'/t' << p2 <<endl;
    //We can only get the string.
    //Let reaffirm it
    if(&p1 == &p2)
    {
        cout<<"The same." <<endl;
    }
    else
    {
        cout<<"Not the same." <<endl;
    }
    return 0;
}

&p其实得到的是指针的地址,而不是c-string “Hello word!”的地址,而cout又为char* 重载了一个不同与一般指针的输出方式,所以你要输出”Hello world!”,可以通过static_cast<void>方式,强制转换到void指针,这样cout就可以输出想要的结果,结果自然和Bjarne Stroustrup说的一样,微软也没有错。

如下:

/*Copyright (c) 2007,九天雁翎

* All rights reserved.

* 和实现有关的相同字符串存储方式检验的思考

* 完成日期:2007年7月7日*/

#include "stdafx.h"

#include "myself.h"

#include <iostream>

using namespace std;

int main()
{
    char *p1 = "Hello the world!";
    char *p2 = "Hello the world!";
    if(p1 == p2)
    {
        cout << "The same."<<endl;          
    }
    else
    {
        cout << "Not the same."<<endl;
    }
    //Yes,it is.
    cout << static_cast<void*>(p1) <<'/t' <<static_cast<void*>(p2) <<endl;
    return 0;
}

分类:  C++ 
标签:  C++ 

By 九天雁翎

2007年07月07日 | 九天雁翎的博客

前一篇: 几种交换方式与参数传递方式效率的比较,发现STL最慢 后一篇: 增加无限长精确整数(infinite precision integer)给C++标准库的提案 简单翻译稿 N1692