auto与typedef与宏(千字长文详解)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了auto与typedef与宏(千字长文详解)相关的知识,希望对你有一定的参考价值。

auto与typedef与宏

#define MAP std::map<std::string, std::string> 
int main()

 MAP m  "apple", "苹果" ,  "orange", "橙子" , "pear","梨" ;
 MAP::iterator it = m.begin();
 while (it != m.end())
 
 //....
 
 return 0;

宏是直接在预编译阶段进行替换

但是宏也是有缺点——例如没有安全类型检查!

typedef

​ 既然宏有缺点,那typedef呢?

#include <string>
#include <map>
typedef std::map<std::string, std::string> map;
int main()

	map m  "apple", "苹果" ,  "orange", "橙子" , "pear","梨" ;
	map::iterator it = m.begin();
	while (it != m.end())
	
		//....
	
	return 0;

答案是也有——会导致变量类型的不准确!

typedef char* pstring;
int main()

    const pstring p1;    //编译失败
    const pstring* p2;   //编译成功
    const pstring p1 = 0;//就可以编译成功了
 return 0;

//const pstring 的实际类型不是 const char* 而是 char* const!

auto(C++11)

auto作为一个新的类型指示符来指示编译器,auto声明的变量必须由编译器在编译时期推导而得

auto的正常使用

int TestAuto()

	return 10;

int main()

	int a = 10;
	auto b = a;
	auto c = a;
	auto d = TestAuto();
    //auto e; 无法通过编译,使用auto定义变量时必须对其进行初始化
	cout << typeid(b).name() << endl;
	cout << typeid(c).name() << endl;
	cout << typeid(d).name() << endl;
	return 0;

auto与指针与引用

int main()

    int x = 10;
    auto a = &x;
    auto* b = &x;
    auto& c = x;
    cout << typeid(a).name() << endl;
    cout << typeid(b).name() << endl;
    cout << typeid(c).name() << endl;
    *a = 20;
    *b = 30;
     c = 40;
    return 0;


auto在同一行定义多个变量

void TestAuto()

    auto a = 1, b = 2; 
    auto c = 3, d = 4.0;  // 该行代码会编译失败,因为c和d的初始化表达式类型不同

当在同一行声明多个变量时,这些变量必须是相同的类型,否则编译器将会报错,因为编译器实际只对第一个类型进行推导,然后用推导出来的类型定义其他变量。

auto不能推导的情况

auto不能作为形参类型

void TestAuto(auto a)

    return;

// 此处代码编译失败,auto不能作为形参类型,因为编译器无法对a的实际类型进行推导

auto不能直接用来声明数组

void TestAuto()

    int a[] =  1,2,3 ;
    auto b[] =  4,5,6 ;

以上是关于auto与typedef与宏(千字长文详解)的主要内容,如果未能解决你的问题,请参考以下文章

c++之引用(五千字长文详解!)

拷贝构造,赋值运算符重载(六千字长文详解!)

C++之string的底层简单实现!(七千字长文详解)

STL之list底层简单实现(七千字长文详解!)

五千字长文详解Istio实践之熔断和限流工作原理

c++之类和对象——类的定义,存储方式,this指针!(五千字长文详解!)