support bazel complie this project and format code.

This commit is contained in:
zhangxing
2023-03-30 00:15:11 +08:00
committed by light-city
parent 1f86192576
commit 7529ae3a55
636 changed files with 10025 additions and 9387 deletions

View File

@@ -0,0 +1,8 @@
# please run `bazel run basic_content/virtual/set4:rtti`
load("@rules_cc//cc:defs.bzl", "cc_binary")
cc_binary(
name = "rtti",
srcs = ["rtti.cpp"],
copts = ["-std=c++11"]
)

Binary file not shown.

View File

@@ -1,34 +1,38 @@
/**
* @file rtti.cpp
* @brief 在面向对象程序设计中有时我们需要在运行时查询一个对象是否能作为某种多态类型使用。与Java的instanceof以及C#的as、is运算符类似C++提供了dynamic_cast函数用于动态转型。相比C风格的强制类型转换和C++ reinterpret_castdynamic_cast提供了类型安全检查是一种基于能力查询(Capability Query)的转换所以在多态类型间进行转换更提倡采用dynamic_cast
* @brief
* 在面向对象程序设计中有时我们需要在运行时查询一个对象是否能作为某种多态类型使用。与Java的instanceof以及C#的as、is运算符类似C++提供了dynamic_cast函数用于动态转型。相比C风格的强制类型转换和C++
* reinterpret_castdynamic_cast提供了类型安全检查是一种基于能力查询(Capability
* Query)的转换所以在多态类型间进行转换更提倡采用dynamic_cast
* @author 光城
* @version v1
* @date 2019-07-24
*/
// CPP program to illustrate
// // Run Time Type Identification
#include<iostream>
#include<typeinfo>
using namespace std;
class B { virtual void fun() {} };
class D: public B { };
// CPP program to illustrate
// Run Time Type Identification
#include <iostream>
#include <typeinfo>
using namespace std;
class B {
virtual void fun() {}
};
class D : public B {};
int main()
{
B *b = new D; // 向上转型
B &obj = *b;
D *d = dynamic_cast<D*>(b); // 向下转型
if(d != NULL)
cout << "works"<<endl;
else
cout << "cannot cast B* to D*";
try {
D& dobj = dynamic_cast<D&>(obj);
cout << "works"<<endl;
} catch (bad_cast bc) { // ERROR
cout<<bc.what()<<endl;
}
return 0;
int main() {
B *b = new D; // 向上转型
B &obj = *b;
D *d = dynamic_cast<D *>(b); // 向下转型
if (d != NULL)
cout << "works" << endl;
else
cout << "cannot cast B* to D*";
try {
D &dobj = dynamic_cast<D &>(obj);
cout << "works" << endl;
} catch (bad_cast bc) { // ERROR
cout << bc.what() << endl;
}
return 0;
}

View File

@@ -1,35 +1,25 @@
// 在使用时需要注意被转换对象obj的类型T1必须是多态类型即T1必须公有继承自其它类或者T1拥有虚函数继承或自定义。若T1为非多态类型使用dynamic_cast会报编译错误。
// A为非多态类型
// A为非多态类型
class A{
class A {};
// B为多态类型
class B {
public:
virtual ~B() {}
};
//B为多态类型
// D为非多态类型
class B{
class D : public A {};
public: virtual ~B(){}
// E为非多态类型
};
//D为非多态类型
class D: public A{
};
//E为非多态类型
class E : private A{
};
//F为多态类型
class F : private B{
}
class E : private A {};
// F为多态类型
class F : private B {}