Interview questions and answers

1. How grep recursively searches a directory for the desired string.

grep -nrw "test" path #Recursively find the test string under the path directory and display the line number

2. Determine whether the binary tree is symmetric.

The main idea is recursion, starting from the root node to judge, if the root node is symmetrical and then recursing the left and right children, the balance returns true, and the imbalance returns false

3. C++ virtual table

If we declare a virtual function in a class, the compiler will insert a pointer to the virtual table at the beginning or end of the class instance (different compilers have different implementations). Each class that has an inheritance relationship or that declares virtual functions will have a virtual table. In the case of a subclass, and the corresponding virtual function is rewritten, the function address in the corresponding slot of the subclass will be modified.

4. How to deal with ambiguity in C++ multiple inheritance if two base classes have member functions/variables with the same name.
4.1. The first case is simpler:

class A {
public:
    virtual void f() {}
};

class B {
public:
    virtual void f() {}
};

class C : public A, public B {
public:
    void f() {}
};

main () {
    C c;
    c.f();
    c.A::f();
    c.B::f();
}

In this case we can use domain operators to deal with ambiguity.
4.2. The second case:

class A {
public:
    virtual void f() {}
};

class B : public A {
public:
    virtual void f() {}
};

class C : public A {
public:
    virtual void f() {}
};

class D : public B, public C {
public:
    void f() {}
}

main() {
    D d;
    d.f(); // ok
    d.B::f(); //ok
    d.C::f(); //ok
    A a = d; //error
}

In the above example, since both B and C inherit from A, when clipping occurs, A does not know which class f function to select, and there will be ambiguity here. The correct way is that both B and C are Virtually inherit A, so that when D inherits B and C, it can ensure that only one instance of A exists in the instance of class D, and there will be no ambiguity.

5. When using the new malloc function, what happens if there is insufficient memory.

When using the memory allocation function, if the memory has been exhausted, new will throw a bad_alloc exception. We can catch this exception and handle the exception. The malloc function will return NULL when there is not enough memory to allocate. We can also judge this. [Mainly a grasp of the possible situations]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325898609&siteId=291194637