C++学习笔记 —— 命名空间、内联函数、按值/引用/指针传递

命名空间

问题出现

比如两个头文件中PeopleA.h和PeopleB.h 我们定义类两个相同的Student类和普通函数func().
而我们在main文件中同时引入了这两个头文件,而如果我们想使用Student类或者普通函数func()时,编译器就不知道我们要使用哪个了。
为了解决命名冲突的问题。

//PeopleA.h
namespace PeopleA
{
class Student
{
private:
	/* data */
public:
	Student(/* args */);
	~Student();
};

int func()
{
}
} // namespace PeopleA

//PeopleB.h
namespace PeopleB
{
class Student
{
private:
	/* data */
public:
	Student(/* args */);
	~Student();
};

int func()
{
}
} // namespace PeopleB

#include "PeopleA.h"
#include "PeopleB.h"
int main()
{
	//显示指明名字空间
	PeopleA::Student std1;
	PeopleA::func();
	PeopleB::Student std1;
	PeopleB::func();
}

使用命名空间的三种方式

  1. 直接使用
int main(){
	PeopleA::Student std1;
	PeopleA::func();
	PeopleB::Student std1;
	PeopleB::func();
	std::cout<<2;
}
  1. 使用using关键字
using std::cout;
using PeopleA::Student;
int main(){
	Student std1; //这时使用的是PeopleA
	cout<<2;
}
  1. 使用using namespace +名字空间 使用该名字空间下的所有成员
using namespace std;
using PeopleA::Student;
int main(){
	cout<<2;
}

内联函数

什么是内联函数

内联函数-C中关键字inline用法解析

​ 如果一些函数被频繁调用,不断地有函数入栈,即函数栈,会造成栈空间或栈内存的大量消耗。


inline char* dbtest(int a) 
{  
    return (i % 2 > 0) ? "奇" : "偶";  
}   
int main()  
{  
    int i = 0;  
    for (i=1; i < 100; i++) 
    {  
        printf("i:%d    奇偶性:%s /n", i, dbtest(i));      
    }  
}

慎用内联

​ 内联能提高函数的执行效率,为什么不把所有的函数都定义成内联函数?
​ 内联是以代码膨胀(复制)为代价,每一处内联函数的调用都要复制代码,将使程序的总代码量增大,消耗更多的内存空间。

内联函数使用

  1. 内联函数不能包括复杂的控制语句,如循环语句和switch语句;
  2. 只将规模很小(一般5个语句一下)而使用频繁的函数声明为内联函数。在函数规模很小的情况下,函数调用的时间开销可能相当于甚至超过执行函数本身的时间,把它定义为内联函数,可大大减少程序运行时间。

引用

引用的实质,就是起别名。
引用必须初始化,不能只声明。

#include <iostream>
#include <cstring>

using namespace std;


int main()
{
   int a = 10;
   int &b = a;//放在等号左边是起别名,放在等号右边是取地址。
   b = 20;
   cout<< a; // 20  修改的就是原a的值
}

按值传递,引用传递,指针传递区别

值传递,引用传递,指针地址传递

#include <iostream>

using namespace std;

class Person
{
public:
	Person(int a) : num(a)
	{
	}
	~Person()
	{
	}
	void setNum(int a)
	{
		num = a;
	}
	void printNum()
	{
		cout << num << endl;
	}

private:
	int num;
};

//按值传递
void passByValue(Person p)
{
	//值传递,相当于创建一个新对象的副本
	p.setNum(100);
	p.printNum();
}
//按引用传递
void passByRef(Person &p)
{
	p.setNum(200);
	p.printNum();
}
//按指针传递
void passByPointer(Person *p)
{
	p->setNum(300);
	p->printNum();
}
int main()
{
	Person p1(0);	//初始化值0
	passByValue(p1); // 100
	p1.printNum();

	Person p2(0);
	passByRef(p2); //200 原对象中值被更改
	p2.printNum(); //200
	//所以一般使用该种方式来进行函数传入对象,因为可以修改传入对象的值,这也是java使用中默认方式传引用。因为java没有&取地址符号。

	Person p3(0);
	passByPointer(&p3); // 300
	p3.printNum();		// 300 传递的是对象的地址,函数对对象的改变直接操作原对象,直接改变
}
发布了103 篇原创文章 · 获赞 94 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/chongbin007/article/details/104216429