Virtual Function in C++

本文通过一个具体的C++示例介绍了虚函数的概念及其工作原理。文章展示了如何通过虚函数实现多态,使得基类指针可以调用派生类中重定义的方法。同时,也对比了虚函数与非虚函数在运行时的不同行为。
//  ---------https://www.geeksforgeeks.org/virtual-function-cpp/

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class base{
public:
	virtual void print(){
		cout<<"print base class"<<endl;
	}
	void show(){
		cout<<"show base class"<<endl;
	}
};
class derive:public base{
public:
	void print(){
		cout<<"print derived class"<<endl;
	}
	void show(){
		cout<<"show derived class"<<endl;
	}
};

int main(int argc, char const *argv[])
{
	base *bptr;
	derive d;
	bptr= &d;
	bptr->print();//Virtual function,所以调用 derived class

	bptr->show();//non-virtual function 调用base class
	return 0;
}

输出:

A virtual function a member function which is declared within base class and is re-defined (Overriden) by derived class.When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function.

 

import random general_questions = [ "What is the capital of France?", "How do I install Python on Windows?", "What is machine learning?", "What does HTTP stand for?", "How can I create a virtual environment in Python?" ] cpp_questions = [ "Explain inheritance in C++.", "What is the difference between stack and heap memory?", "How do you declare a constant variable in C++?", "What is a virtual function in C++?", "What is the purpose of the 'new' operator in C++?" ] answers = { general_questions[0]: "The capital of France is Paris.", general_questions[1]: "To install Python on Windows, download the installer from python.org and run it. Make sure to check the box that says 'Add Python to PATH' during installation.", general_questions[2]: "Machine learning is a subset of artificial intelligence that involves training algorithms to make predictions or decisions based on data.", general_questions[3]: "HTTP stands for HyperText Transfer Protocol, which is used for transmitting web pages over the internet.", general_questions[4]: "You can create a virtual environment using the command 'python -m venv env_name' followed by activating it with 'source env_name/bin/activate' on Unix or 'env_name\\Scripts\\activate' on Windows.", cpp_questions[0]: "Inheritance in C++ allows a class (called a derived or child class) to inherit properties and methods from another class (known as the base or parent class)[^2].", cpp_questions[1]: "Stack memory is automatically managed by the system, while heap memory requires manual allocation and deallocation using functions like malloc() or new. Stack is faster but limited in size, whereas heap is larger but slower to access.", cpp_questions[2]: "You can use the const keyword before the data type when declaring a variable, for example: const int value = 10;", cpp_questions[3]: "A virtual function is a member function in a base class that is expected to be redefined in derived classes. It enables dynamic dispatch through pointers or references to the base class.", cpp_questions[4]: "The 'new' operator is used to dynamically allocate memory on the heap for an object or array and returns a pointer to the allocated memory." } with open("cplus_faq_5000_pairs.txt", "w") as f: for i in range(5000): q_type = random.choice(["general", "cpp"]) if q_type == "general": question = random.choice(general_questions) else: question = random.choice(cpp_questions) answer = answers[question] f.write(f"{question}|{answer}\n")转话为c++
最新发布
07-12
### 将 Python 代码转换为 C++ 的通用方法 在将 Python 代码转换为 C++ 时,需要考虑语言特性、标准库差异、类型系统以及内存管理等方面的不同。Python 是动态类型、自动垃圾回收的语言,而 C++ 是静态类型、手动或 RAII(资源获取即初始化)风格管理资源的语言。 #### 基本结构映射 Python 中的函数可以映射为 C++ 的函数,类和对象则保持类似的封装方式。例如,一个简单的生成随机数并写入文件的 Python 程序: ```python import random with open('data.txt', 'w') as f: for _ in range(5000): num = random.randint(0, 9999) f.write(str(num) + '\n') ``` 可以转换为如下 C++ 代码,使用了 `<fstream>` 和 `<random>` 标准库组件: ```cpp #include <iostream> #include <fstream> #include <random> int main() { std::ofstream out("data.txt"); std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dist(0, 9999); for(int i = 0; i < 5000; ++i) { int value = dist(gen); out << value << std::endl; } out.close(); return 0; } ``` 该实现保留了原始程序的功能,并利用 C++ 的强类型系统和资源管理机制确保程序的健壮性[^1]。 #### 数据结构与容器替换 Python 中常用的列表(`list`)可对应到 C++ 的 `std::vector` 或 `std::array`,字典(`dict`)对应 `std::unordered_map`,集合(`set`)对应 `std::unordered_set`。例如: ```python my_list = [1, 2, 3] my_dict = {'a': 1, 'b': 2} ``` 等价于: ```cpp #include <vector> #include <unordered_map> std::vector<int> my_list = {1, 2, 3}; std::unordered_map<std::string, int> my_dict = {{"a", 1}, {"b", 2}}; ``` #### 控制结构与异常处理 Python 的 `for` 循环和 `while` 循环可以直接映射到 C++。异常处理方面,Python 使用 `try-except`,C++ 使用 `try-catch`,语法类似但语义略有不同: ```python try: x = 1 / 0 except ZeroDivisionError: print("Cannot divide by zero") ``` 等价于: ```cpp #include <iostream> #include <stdexcept> try { int x = 1 / 0; } catch (const std::runtime_error& e) { std::cout << "Cannot divide by zero" << std::endl; } ``` 注意:C++ 中整数除以零不会抛出异常,需手动检测并抛出异常,上述示例仅为说明语法结构。 #### 文件操作与 I/O 流 Python 的 `with open(...)` 结构在 C++ 中通过局部对象生命周期自动管理资源来实现,即 RAII 模式。打开文件后无需手动关闭,作用域结束时会自动析构流对象并释放资源[^1]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值