c++ 转型为 引用类型 的作用
2014-08-23 21:10
309 查看
情景:近来看到
1.《深入浅出MFC》中p128 有如此语句:
ar >> (WORD&) m_center.x;
ar >> (WORD&) m_center.y;
ar >> (WORD&) m_radius;
之前也知道这几句无非就是提取数据放到这里面,但没有弄清为什么要加一个 & 符号,都是囫囵吞枣,照猫画虎的学着做。。
2. 还有, 微软预定义的 #define _ADDRESSOF(v) ( &reinterpret_cast<const char &>(v) )。
test
结论:对于非内置类型的,如果不加上& 的话,会因为转型而产生临时对象。
对于内置类型的,则是一样。。
ps. vs2010 编译器对于好些产生临时对象的,已经优化的不错了。。
ps. 纯好奇之作, 屠龙之技也,不足一看..
1.《深入浅出MFC》中p128 有如此语句:
ar >> (WORD&) m_center.x;
ar >> (WORD&) m_center.y;
ar >> (WORD&) m_radius;
之前也知道这几句无非就是提取数据放到这里面,但没有弄清为什么要加一个 & 符号,都是囫囵吞枣,照猫画虎的学着做。。
2. 还有, 微软预定义的 #define _ADDRESSOF(v) ( &reinterpret_cast<const char &>(v) )。
test
#include "stdafx.h" #include<iostream> using namespace std; class Int { public: int a; Int(int _a) : a(_a) { cout << " Construct Int... " << endl; } }; class TwoInt { public: int b; int c; TwoInt(int _b, int _c) : b(_b), c(_c) { cout << "Construct TwoInt.. " << endl; } }; // 注意看 cin 对象的 >>, // 在istrem文件中如此定放 _Myt& __CLR_OR_THIS_CALL operator>>(unsigned short& _Val){...} 的定义就知了 void testFunc(Int& i) { cout << "testFunc() : " << i.a << endl; i.a = 5000; } // 测试下内置类型时的情况 void test(int& i) { i = 845556; } int main() { TwoInt testVar(12, 99); #if 1 testFunc((Int&)testVar.b); // 注意看这两句打印出的信息,或是反汇编出来观察 #else testFunc((Int)testVar.b); #endif cout << testVar.b << endl; // 也注意观察这句对应于上面两种情况转出的变化。 // 以下内容测试下内置类型的情况 cout << "==============================" << endl; // 注意看这里 VS2010 反汇编出来是一样的 test((int&)testVar.b); //010815F1 mov eax,dword ptr [testVar] //010815F4 push eax //010815F5 call test (1081262h) //010815FA add esp,4 test(testVar.b); //010815FD mov eax,dword ptr [testVar] //01081600 push eax //01081601 call test (1081262h) //01081606 add esp,4 cout << testVar.b << endl; }
结论:对于非内置类型的,如果不加上& 的话,会因为转型而产生临时对象。
对于内置类型的,则是一样。。
ps. vs2010 编译器对于好些产生临时对象的,已经优化的不错了。。
ps. 纯好奇之作, 屠龙之技也,不足一看..
相关文章推荐
- c++中,static,和const,以及引用类型的作用
- 新手入门:C++下的引用类型
- C++派生类型的作用
- C#中的引用类型与C++中的引用
- C++ 引用的作用和用法
- C++ 引用的作用和用法
- C++下的引用类型
- C++引用类型
- more effective c++ 第一章读书笔记: 指针,引用,c++类型转换,多态数组,默认构造函数
- C++中的引用数据类型
- C++引用类型学习
- 存储类型、作用域、可见性和生存期C++
- C++返回引用类型 指针的引用
- C++ 返回值类型与引用类型的区别
- C++的引用类型
- 浅谈C++/CLI中引用类型的栈对象
- C++模板应用——在类模板实现中引用其内部定义的复合数据类型
- c++数据类型--指针、字符串、const、引用
- C++的引用类型详解
- C++的引用类型