你真的懂C++嗎?

mariocanfly發表於2024-10-12

看看下面的程式碼,你真的懂C++嗎?


```cpp #define N 2 #define M N + 1 #define NUM (M + 1) * M / 2 int main(){ std::cout << NUM; return 0; } // 輸出結果為 8, 展開過程如下 // (M + 1) * M / 2 // (N + 1 + 1) * N + 1 / 2 // (2 + 1 + 1) * 2 + 1 / 2 // 4 * 2 + 0 // 8 ```
```cpp cout << sizeof(i++) << endl; //程式碼執行之後,i並沒有加1 ```
```cpp #include #include using namespace std; class Animal { public: virtual void eat() const { cout << "Animal eats" << endl; } virtual ~Animal(){} };

class Dog : public Animal {
public:
virtual void eat() {
cout << "Dog eats" << endl;
}
virtual ~Dog(){}
};

int main() {
Animal *animal = new Dog();
Dog dog = new Dog();
animal->eat();
dog->eat();
delete animal;
delete dog;
return 0;
}
/

上面的程式碼輸出為:
Animal eats
Dog eats
如果把第一個Animal類的const去掉,就會輸出
Dog eats
Dog eats
這是因為C++多型規定,基類和派生類中同名虛擬函式的函式名、返回值型別、函式引數個數及引數型別等必須完全相同。
如果基類的虛擬函式後面沒有加const,派生類同名的函式後面加了const,那麼派生類的函式沒有起到虛擬函式的作用。
*/

<hr>
```cpp
int number = 1;
auto func1 = [=]() { return number; };
auto func2 = [&]() { return number; };
number++;
std::cout << func1() << ' ' << func2();  //輸出 1 2

```cpp #include using namespace std;

double Up(double x) { return 2.0 * x; }
void R1(const double &rx) { cout << "const double & rx" << endl; }
void R1(double &&rx) { cout << "double && rx" << endl; }

int main()
{
double w = 10.0;
R1(w + 1); // 輸出 double && rx
R1(Up(w)); // 輸出 double && rx
return 0;
}

<hr>
```cpp
auto myTuple = make_tuple<int,int,bool,char>(1,2,true,'C');
auto otherTuple = make_tuple<int,int,bool,char>(1,3, true, 'C' );
cout << sizeof(myTuple) << endl;  //輸出 12, 不同機器結果不同
cout << tuple_size<decltype(myTuple)>::value << endl;  //輸出元素數量 4

```cpp #include

void Foo(const int &) {std::cout << "const l-ref" << std::endl;}
void Foo(int &) {std::cout << "l-ref" << std::endl;}
void Foo(int &&) {std::cout << "r-ref" << std::endl;}

template <typename ...Args>
void ForwardRef(Args&& ...args) {
Foo(std::forward(args)...);
}
int main(){
ForwardRef(1); //輸出r-ref
int x = 1; ForwardRef(x); //輸出l-ref
int& y = x; ForwardRef(y); //輸出l-ref
const int& z = x; ForwardRef(z); //輸出const l-ref
return 0;
}

<hr>
```cpp
int a = 5;
static int b = 3;
auto funca = [=]() mutable {
    ++a; return a;
};
auto funcb = [=]() mutable {
    ++b; return b;
};
cout << funca() << " " << funcb() << endl; // 輸出 6 4
cout << funca() << " " << funcb() << endl; // 輸出 7 5
cout << a << " " << b << endl;             // 輸出 5 5

```cpp enum Status {GOOD = -1, BAD, UNKNOWN}; cout << UNKNOWN << endl; //輸出 1 cout << static_cast(static_cast(UNKNOWN) - 1) << endl; //輸出 0 ```
```cpp #include using namespace std; class Base { public: Base(int a) : varA(a) {} int varA; }; class Derived : public Base { public: int varB; int varC; Derived(int a, int c) : varC(c), Base(a), varB(varA + varC) {} };

Derived derived(1, 10); // 全域性變數

int main() {
cout << derived.varA << " " << derived.varB << " " << derived.varC << " " << endl;
// 輸出 1 1 10
// 按照宣告的順序初始化而不是列表的順序,這裡初始化順序是 varA,varB,varC,由於varB要被賦值為varA + varC時,
// varC還沒有賦值,所以此時varC = 0,varB被賦值為varA=1
// 但是,把 Derived derived(1, 10) 放到int main()裡面,情況又會不一樣,這個我也解釋不了。
return 0;
}

<hr>
```cpp
#include <iostream>
class BaseException {};
class DerivedException:public BaseException {};
int main() {
    try {
        BaseException* except = new DerivedException();
        throw *except;
    } catch (DerivedException&) {
        std::cout << "DerivedException";
    } catch (BaseException&) {
        std::cout << "BaseException";
    } catch (...) {
        std::cout << "other Exception";
    }
    // 輸出 BaseException
}

假設有以下程式碼:

class MyData {
public:
	MyData() : value(5) {}
private:
	int value;
};

void Func()
{
std::vector<MyData> myVector;
// ……對myVector進行了一些操作
____ // 想要新增一個元素到myVector中
}

橫線處的程式碼想要新增一個MyData物件到myVector容器中,並且要求新增的這個MyData物件中value成員的值是5。下面程式碼可以正確完成這個動作:

myVector.push_back(MyData());
myVector.insert(myVector.end(), MyData());
myVector.resize(myVector.size() + 1);
//但是當myVector為空時,*(myVector.end()) = MyData(); 會報錯

const int a = 128;
//以下都是無法透過的程式碼:
int * const b = &a;
int *b = &a;
int &b = a;
//以下是可以透過的程式碼:
const int &b = a;
const int *b = a;
int const *b = a;

//複製構造、移動構造、複製賦值、移動賦值你會寫嗎?
class A {
public:
    A() {
        cout << "Default constructor" << endl;
    }
    A(const A& a) {
        cout << "Copy constructor" << endl;
    }
    A(A&& a) {
        cout << "Move constructor" << endl;
    }
    A& operator=(const A& p) {
        cout << "Copy assign" << endl;
    }
    A& operator=(A&& other) {
        cout << "Move assign" << endl;
    }
};

相關文章