C++常见面试题(一)C/C++区别 const用法

1.C与C++的区别

a.C是面向过程的语言 C++是面向对象的语言

b.C中函数不能进行重载 C++函数可以重载

c.C函数的参数如果没有写void即是可变参数,形如 int sum() ;C++中int sum()则为空函数

d.C中struct中不能有函数 C++中可以有函数


2.Const的一些用法

const修饰函数时候

修饰函数返回值和类的成员函数函数体时注意事项如下

#include<iostream>

using namespace std;

const int a()//返回值为const 
{
	return 3;
}

class A
{
	public:
		
		int temp;
		int fun (int x)const//类中成员函数的函数体由const修饰时,不能改变成员变量的值 
  		{
			//temp=5;//修改了temp的值,出错 
			return 0;
		}
};

int main()
{
   //int v=a();//a()只能作为右值,可以赋给int v和const int v 
   const int v=a(); 
   cout<<v;
   A a;
   a.fun(5);
   return 0;
}


const修饰函数参数时,参数值不能改

#include<iostream>

using namespace std;

int fun(const int a)
{
	//a=3;//不能改变参数的值
	int b=6;//可以改变
	return 0; 
}

int main()
{
   fun(7);
   return 0;
}

const修饰变量时

#include<iostream>

using namespace std;


int main()
{
   int b=4;
   int c=5;
   const int *a= &b;//const 在*左边,指针指向的内容为常量 即a的内容为常量 
   int const *a=&b;//效果如上相同
   a=&c;//可以改变a的指向 
  // *a=9;//错误:但是不能改变a的内容 
  
   cout<<*a; 
   return 0;
}


#include<iostream>

using namespace std;


int main()
{
   int b=4;
   int c=5;
   int *const a=&b;//const在*号的右边,表明指针a是常量不能进行修改,但是a指的内容是可以修改的 
   //a=&c;//错误:指针a的指向不能修改 
   *a=7; 
  
   cout<<*a; 
   return 0;
}


#include<iostream>

using namespace std;


int main()
{
   int b=4;
   int c=5;
   const int *const a=&b;//const在*号的两边都有,表明指针a是常量不能进行修改,但是a指的内容是也不可以修改的 
   //a=&c;//错误:指针a的指向不能修改 
   //*a=7; //错误:指针a指的内容不能修改 
  
   cout<<*a; 
   return 0;
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值