常见C ++面试问题
在这里,我们将看到一些重要的C++面试问题。
C和C++有什么区别?
指针和引用之间有什么区别?
指针和引用之间的主要区别是-
引用用于引用另一个名称中的现有变量,而指针用于存储变量的地址。
引用不能分配空值,但指针可以。
引用变量可以按值传递,而指针可以引用但按引用传递。
必须在声明时初始化引用,而在使用指针的情况下则不需要。
引用与原始变量共享相同的内存地址,但也占用堆栈上的一些空间,而指针在堆栈上有其自己的内存地址和大小
什么是C++中的虚函数?
C++中的虚函数用于创建基类指针和任何派生类的调用方法的列表,甚至不知道派生类对象的种类。虚函数在运行时解析得较晚。
如果基类中的虚函数声明为成员函数一次,则它在从该基类派生的每个类中均变为虚函数。因此,在声明虚拟基类函数的重新定义版本时,在派生类中不必使用关键字virtual。
示例
#include<iostream>
using namespace std;
class B {
public:
virtual void s() {
cout<<" In Base \n";
}
};
class D: public B {
public:
void s() {
cout<<"In Derived \n";
}
};
int main(void) {
D d; // An object of class D
B *b= &d; // A pointer of type B* pointing to d
b->s(); // prints"D::s() called"
return 0;
}输出结果
In Derived
C++中的这个指针是什么?
C++中的每个对象都可以通过称为此指针的重要指针访问其自己的地址。this指针是所有成员函数的隐式参数。因此,在成员函数内部,这可以用于引用调用对象。
友元函数没有this指针,因为朋友不是类的成员。仅成员函数具有this指针。
让我们尝试以下示例以了解此指针的概念-
示例
#include <iostream>
using namespace std;
class Box {
public:
//构造函数定义
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"构造函数称为。" << endl;
length = l;
breadth = b;
height = h;
}
double Volume() {
return length * breadth * height;
}
int compare(Box box) {
return this->Volume() > box.Volume();
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
if(Box1.compare(Box2)) {
cout << "Box2 is smaller than Box1" <<endl;
} else {
cout << "Box2 is equal to or larger than Box1" <<endl;
}
return 0;
}输出结果
构造函数称为。 构造函数称为。 Box2 is equal to or larger than Box1