c++中那些奇怪的事情

  • content {:toc}

引用来实现多态

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include<iostream>
using namespace std;

class Base {
public:
    virtual void print() {
        cout << "This is Base class." << endl;
    }
};

class Derived : public Base {
public:
    void print() {
        cout << "This is Derived class." << endl;
    }
};

int main() {
    Derived derivedObj;
    Base& baseRef = derivedObj;  // 使用基类引用引用派生类对象

    baseRef.print();  // 调用的是 Derived 类中的 print 函数

    return 0;
}

不涉及多态时, 删除对象会发生什么

  • 结果, 还能运行函数
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#include<iostream>
using namespace std;

class Base {
public:
     void print() {
        cout << "This is Base class." << endl;
    }
};



int main() {
    Base * p = new Base();
  delete(p);
  p-> print();
  cout<< "success"<< '\n';
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
using namespace std;

class Base {
public:
     void print() {
        cout << "This is Base class." << endl;
       cout<< "a = "<< a <<'\n';
    }
  int a = 0;
};



int main() {
    Base * p = new Base();
  p->print(); // a = 0;
  delete(p); 
  p-> print(); // a = 5898


    return 0;
}
Licensed under CC BY-NC-SA 4.0
最后更新于 Oct 13, 2024 18:49 +0800
使用 Hugo 构建
主题 StackJimmy 设计