C++重载相关面试问题

C++重载相关面试问题

1 什么是重载,重载的定义是什么?

  • 重载是指是相同的作用域内的一组具有相同函数名,不同参数列表的函数。
  • 一个简单的例子如下:
int foo(int a);
int foo(int a, int b); //参数个数不同
int foo(double a); //参数类型不同

2 重载函数为什么不能返回值来区分?

  • 对这个问题,我个人的理解是:
    • 以返回值来区分,会引入上下文关连
    • 如果在调用时不指定返回值的类型,编译器将无法选择调用哪个函数
int foo(int a);
double foo(int a);
//以上两个函数仅是返回值不同

int a = foo(1);
double b = foo(2); //上下文关连

foo(3) // ??? 调哪个函数呢?

3 重载(overload)与重写(override)的区别是什么?

  • 重载必须在同一个作用域内,重写发生在基类和派生类之间且基类函数必须要有virtual关键字
  • 重载的函数参数列表必须不同,重写的函数参数个数相同,类型兼容。

看下面的例子, 基类中定义了foo函数且加入virtual关键字,派生类中的foo与基类参数相同:

class B
{
public:
	virtual void foo(int a)
	{
		cout << "B::foo(int)" << endl;
	}
};

class C : public B
{
public:
	void foo(int a)
	{
		cout << "C::foo(int)" << endl;
	}
};


int main()
{
	B b;
	C c;
	B *pb;

	pb = &b;
	pb->foo(1);
	pb = &c;
	pb->foo(1);
	return 0;
}

输出结果为:

B::foo(int)
C::foo(int)

修改class C中的foo定义为:

void foo(float a);

则输出变为:

B::foo(int)
B::foo(int)

可见还是调用的基类的foo, class C的foo没有被override, 而是被redefining了。 如果将class C中的foo定义为:

void foo(const int a);

输出结果为:

B::foo(int)
C::foo(int)

Override又成功了,可见const关键字不会影响override.

4 什么是重定义(redefining)?

  • 重定义是指派生类中的函数屏蔽了基类中相同名字的函数
    • 派生类中的函数与基类中函数的名字相同,但参数不同,不管有无virtual, 基类中的函数被覆盖
    • 派生类中的函数与基类中函数的名字相同,参数也相同,但无virtual关键字,基类中的函数被覆盖

5 请写出++操作符的前缀(prefix)和后缀(postfix)重载函数?

#include <iostream>
#include <stdio.h>
using namespace std;

class A 
{
public:
	A() : a(0) {}
	A(int i) : a(i) {}
	A& operator++();
	A operator++(int);
	friend ostream& operator <<(ostream&, A&);
	friend A operator +(A &a1, A &a2);
private:
	int a;
};

ostream& operator <<(ostream &output, A &a)
{
	output << "A is " << a.a << endl;
	return output;
}

// prefix, ++A
A& A::operator++()
{
	++a;
	cout << "++A" << endl;
	return *this;
}
// postfix, A++
A A::operator++(int)
{
	A t = *this;
	a++;
	cout << "A++" << endl;
	return t;
}

A operator +(A &a1, A &a2)
{
	return A(a1.a + a2.a);
}

int main()
{
	A a;
	a++;
	++a;
	cout << ++a;
	A a1(1);
	A a2(2);
	a = a1 + a2;
	cout << a;
	return 0;
}

Created: 2015-03-09 周一 20:38

Emacs 24.4.1 (Org mode 8.2.10)

Validate

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值