Skip to content

C++ 基础知识回顾

  1. 作用域与变量生命周期

C++
#include <iostream>
using namespace std;

int main() {
    int x = 10;
    {
        int x = 20;
        cout << "Inner x: " << x << endl;
    }
    cout << "Outer x: " << x << endl;
    return 0;
}

问题:输出是什么?为什么?

  1. 函数重载与类型转换

c++
#include <iostream>
using namespace std;

void func(int x) {
    cout << "int version" << endl;
}

void func(double x) {
    cout << "double version" << endl;
}

int main() {
    func(5);
    func(5.0);
    func('a');
    return 0;
}

问题:输出是什么?为什么?

  1. 指针与引用的区别

c++
#include <iostream>
using namespace std;

void modify(int* ptr, int& ref) {
    *ptr = 10;
    ref = 20;
}

int main() {
    int a = 5, b = 5;
    modify(&a, b);
    cout << "a: " << a << ", b: " << b << endl;
    return 0;
}

问题:输出是什么?为什么?

  1. 数组名的本质

c++
#include <iostream>
using namespace std;

int main() {
    int arr[5] = {1, 2, 3, 4, 5};
    cout << sizeof(arr) << endl;
    cout << sizeof(arr + 0) << endl;
    return 0;
}

问题:输出是什么?为什么? 5. ### 构造函数与初始化列表

c++
#include <iostream>
using namespace std;

class Test {
public:
    int x;
    Test(int val) : x(val) {}
};

int main() {
    Test t = 10;
    cout << t.x << endl;
    return 0;
}

问题:代码是否能编译?为什么? 6. ### 虚函数与静态绑定

c++
#include <iostream>
using namespace std;

class Base {
public:
    virtual void show() { cout << "Base" << endl; }
};

class Derived : public Base {
public:
    void show() { cout << "Derived" << endl; }
};

int main() {
    Base b;
    Derived d;
    Base* ptr = &d;
    ptr->show();
    return 0;
}

问题:输出是什么?为什么? 7. ### 复制构造函数与临时对象

C++
#include <iostream>
using namespace std;

class Test {
public:
    Test() { cout << "Default Constructor" << endl; }
    Test(const Test&) { cout << "Copy Constructor" << endl; }
};

void func(Test t) {}

int main() {
    Test t1;
    func(t1);
    return 0;
}

问题:输出是什么?为什么? 8. ### const 成员函数

#include <iostream>
using namespace std;

class Test {
public:
    int x;
    void setX(int val) const { x = val; }
};

int main() {
    Test t;
    t.setX(10);
    return 0;
}

问题:代码是否能编译?为什么?

  1. 右值引用与移动语义

c++
#include <iostream>
using namespace std;

void func(int&& x) {
    cout << "Rvalue reference: " << x << endl;
}

int main() {
    int a = 5;
    func(a);
    func(10);
    return 0;
}
  1. 静态局部变量

#include <iostream>
using namespace std;

void func() {
    static int x = 0;
    cout << x++ << endl;
}

int main() {
    func();
    func();
    func();
    return 0;
}

输出是什么?为什么?