任何人都可以解释重新解释强制转换如何在此代码中工作

时间:2015-10-08 05:47:28

标签: c++ reinterpret-cast

阅读以下正在使用的程序 的reinterpret_cast。

using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
using System.Text;
using System.Web.Script.Serialization;

namespace ConsoleApplication2
{
    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebGet]
        string EchoWithGet(string s);

        [OperationContract]
        [WebInvoke]
        string EchoWithPost(string s);

        [OperationContract]
        [WebInvoke]
        string EchoWithTest(string s);

        [OperationContract]
        [WebInvoke]
        string EchoPerson();
    }

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public double Shoesize { get; set; }

    }

    public class Service : IService
    {
        public string EchoWithGet(string s)
        {
            return "You said " + s;
        }

        public string EchoWithTest(string s)
        {
            return "You said " + s;
        }

        public string EchoWithPost(string s)
        {
            return "You said " + s;
        }

        //[WebInvoke(Method = "GET",
        //    ResponseFormat = WebMessageFormat.Json,
        //    UriTemplate = "data/{id}")]
        public string EchoPerson()
        {
            Person testPerson = new Person()
            {
                Name = "TestPerson",
                Age = 12,
                Shoesize = 9.5
            };

            string s1 = new JavaScriptSerializer().Serialize(testPerson);

            return s1;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            WebServiceHost host = new WebServiceHost(typeof(Service), new Uri("http://localhost:8000/"));
            try
            {
                ServiceEndpoint ep = host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), "");
                host.Open();
                using (ChannelFactory<IService> cf = new ChannelFactory<IService>(new WebHttpBinding(), "http://localhost:8000"))
                {
                    cf.Endpoint.Behaviors.Add(new WebHttpBehavior());

                    IService channel = cf.CreateChannel();

                    string s;

                    Console.WriteLine("Calling EchoWithGet via HTTP GET: ");
                    s = channel.EchoWithGet("Hello, world");
                    Console.WriteLine("   Output: {0}", s);

                    Console.WriteLine("");
                    Console.WriteLine("This can also be accomplished by navigating to");
                    Console.WriteLine("http://localhost:8000/EchoWithGet?s=Hello, world!");
                    Console.WriteLine("in a web browser while this sample is running.");

                    Console.WriteLine("");
                    s = channel.EchoPerson();
                    Console.WriteLine("   Output: {0}", s);

                    Console.WriteLine("Calling EchoWithPost via HTTP POST: ");
                    s = channel.EchoWithPost("Hello, world");
                    Console.WriteLine("   Output: {0}", s);
                    Console.WriteLine("");
                }

                Console.WriteLine("Press <ENTER> to terminate");
                Console.ReadLine();

                host.Close();
            }
            catch (CommunicationException cex)
            {
                Console.WriteLine("An exception occurred: {0}", cex.Message);
                Console.ReadLine();
                host.Abort();
            }

        }
    }
}

运行此程序后打印0,任何人都可以解释 为什么z在这个程序中会出错?

2 个答案:

答案 0 :(得分:5)

  

任何人都可以解释重新解释强制转换如何在此代码中起作用

reinterpret_cast<char*>(pa)求值为char*类型的指针,其数值与pa的数值相同。使用:

bool z = (pa == pb);

导致编译器错误,因为AB没有直接关系。使用

bool z = (reinterpret_cast<char*>(pa) == reinterpret_cast<char*>(pb));

允许您比较papb的数值。

  

运行此程序后打印0,任何人都可以解释为什么z在这个程序中出现错误吗?

papb的数值不相同。因此,结果。您可以使用:

cout << "pa: " << std::hex << (void*)pa << std::endl;
cout << "pb: " << std::hex << (void*)pb << std::endl;

打印这些值并说服自己不一样。

如果你看一下C的内存布局,它看起来像是:

+------+
|  m_i |     // The A sub-object
+------+
|  m_d |     // The B sub-object
+------+
|  m_c |     
+------+

使用时

C c;
A* pa = &c;
B* pb = &c;

pa指向A的{​​{1}}子对象,C指向pb的{​​{1}}子对象。从图中可以看出,B子对象和C子对象之间存在偏移。因此,AB的数值不同。最有可能因pa而异。

答案 1 :(得分:0)

reinterpret_cast与static_cast相同。 reinterpret_cast在运行时发生,而static_cast在编译时发生。在这种情况下没有区别,但是如果将强制转换应用于对象c,则会产生影响。

A* pa = &reinterpret_cast<A&>(c); 
B* pb = &reinterpret_cast<B&>(c); 

会使pa和pb相同。虽然您有效地编写了隐式静态强制转换:

A* pa = &static_cast<A&>(c); 
B* pb = &static_cast<B&>(c);

由于这会使pa和pb不同,因此以后重新解释&#34;并不重要。