From e77d832dcb92abc98e208f73aa8136736526f7fb Mon Sep 17 00:00:00 2001 From: hthuz Date: Wed, 11 Sep 2024 22:56:42 +0800 Subject: [PATCH] add: c++ virtual override --- .gitignore | 2 -- cpp/override.cpp | 23 +++++++++++++++++++++++ cpp/string.cpp | 26 ++++++++++++++++++++++++++ 3 files changed, 49 insertions(+), 2 deletions(-) create mode 100644 cpp/override.cpp create mode 100644 cpp/string.cpp diff --git a/.gitignore b/.gitignore index 05fd24c..62014db 100644 --- a/.gitignore +++ b/.gitignore @@ -2,8 +2,6 @@ c/*.out c/*.o cpp/*.out -cpp/ -!cpp/*.cpp java/*.class diff --git a/cpp/override.cpp b/cpp/override.cpp new file mode 100644 index 0000000..8c89640 --- /dev/null +++ b/cpp/override.cpp @@ -0,0 +1,23 @@ + +#include + + +class Expression_class { +public: + // Without virtual, the program will gives 0; => Based on declared type + // With virtual => Based on derived classes + virtual bool is_no_expr() {return false;} +}; + +typedef Expression_class* Expression; + +class no_expr_class : public Expression_class { +public: + bool is_no_expr() {return true;} +}; + +int main() { + // Compiler makes decision based on static type information available at compile time + Expression expr = new no_expr_class(); + std::cout << expr->is_no_expr() << std::endl; +} diff --git a/cpp/string.cpp b/cpp/string.cpp new file mode 100644 index 0000000..454bc6d --- /dev/null +++ b/cpp/string.cpp @@ -0,0 +1,26 @@ + +#include +#include +using namespace std; + +int main() { + string str; + str = "amazing"; + cout << str << endl; + str = "amaz\"ing"; + cout << str << endl; + str = "amaz\"in\"g"; + cout << str << endl; + str = "amazi""ng"; + cout << str << endl; + str = "amaz'ing"; + cout << str << endl; + str = "ama'z'ing"; + cout << str << endl; + str = "ama\'zing"; + cout << str << endl; + + + +} +