C++——类型转换杂记

const_cast 和 static_cast int x = 65536; (short &)x = 65535; cout<<x; int main() { const int x = 0; *(int*)&x = 2; cout << "x = " << x << endl; // x = 0 (int&)x = 3; int y = x; cout << "y = " << y << endl; // y = 0 const_cast<int&>(x) = 10; y = x; cout << "y = " << y << endl; // y = 0 return 0; } struct T{ int x = 0; const int y = 0; int q() const{ *(int*)&y = y + 1; return y; } }; int main() { T m; const T n; int x = m....

September 15, 2022 · 4 min · Rick Cui

C++——类型转换

September 14, 2022 · 0 min · Rick Cui

C++——运算符重载

September 14, 2022 · 0 min · Rick Cui

C++——异常的使用

普通函数、lambda表达式、函数模板和模板实例函数都可以定义异常接口 指针和引用类型的异常都可以支持多态 catch 的子类异常一定要写在父类异常的上面,catch 执行后就不会再执行后面的 catch 语句了 对于指针异常,如果不打算向上抛出,一定要记得 delete const volatile void * 可以捕获抛出的任何指针异常 ... 可以捕获抛出的任何异常 不引发任何异常,在函数后面添加 throw()、throw(void)、noexcept 建议将 noexcept 应用到任何绝不允许异常传播到调用堆栈的函数,当函数被声明为 noexcept 时,它使编译器可以在多种不同的上下文中生成更高效的代码 Exception.h struct A { int a = 1; virtual int getA()const { return a; } }; struct B : A { int a = 2; int getA()const override { return a; } }; #define cout cout<<__FILE__<<":"<<__LINE__<<": Exception: " void testException() { try { // 抛出子类指针类型的异常 //throw new B; // 抛出子类对象类型的异常 throw B(); } catch (const A e) { cout << e....

September 14, 2022 · 2 min · Rick Cui

C++——多继承与虚基类

案例一: class A { public: int a; A(int x) :a(x) { } }; class B : public A { public: B(int x) :A(x) { // 这里初始化的是派生树中正常的基类 A } }; class C { public: C() { } }; class D : virtual public A, public C { public: D(int x) :A(x) { } }; class E : /*public A,*/ public B, public D { // 不允许存在直接基类和间接虚基类的情况 public: E(int x) : A(x), B(x + 5), D(x + 10) { // error C2385: 对“A”的访问不明确 // 所以要使用 B::A(x) 或者 D::A(x) // 此时初始化的都是派生树中虚基类 A } }; int main(){ E e(0); //cout << e....

September 12, 2022 · 2 min · Rick Cui