请举出C++动态内存的实际使用场景并给出源码
C++动态内存的实际使用场景包括动态数组、动态创建对象和动态分配内存等。
- 动态数组:动态数组在需要在程序运行时根据需要分配和释放内存的情况下非常有用。下面是一个使用动态数组的示例:
#include <iostream>
int main() {
int size;
std::cout << "Enter the size of the array: ";
std::cin >> size;
int* numbers = new int[size];
for (int i = 0; i < size; ++i) {
numbers[i] = i;
}
std::cout << "Array elements: ";
for (int i = 0; i < size; ++i) {
std::cout << numbers[i] << " ";
}
delete[] numbers;
return 0;
}
- 动态创建对象:有时候需要在程序运行时动态创建对象,比如根据用户的输入创建不同类型的对象。下面是一个使用动态创建对象的示例:
#include <iostream>
class Shape {
public:
virtual void draw() = 0;
};
class Circle : public Shape {
public:
void draw() {
std::cout << "Drawing a circle." << std::endl;
}
};
class Square : public Shape {
public:
void draw() {
std::cout << "Drawing a square." << std::endl;
}
};
int main() {
int choice;
std::cout << "Enter 1 for circle, 2 for square: ";
std::cin >> choice;
Shape* shape;
if (choice == 1) {
shape = new Circle();
} else if (choice == 2) {
shape = new Square();
} else {
std::cout << "Invalid choice." << std::endl;
return 0;
}
shape->draw();
delete shape;
return 0;
}
- 动态分配内存:有时候需要在程序运行时动态分配内存来存储数据,比如读取未知长度的字符串。下面是一个使用动态分配内存的示例:
#include <iostream>
int main() {
int length;
std::cout << "Enter the length of the string: ";
std::cin >> length;
char* str = new char[length + 1]; // +1 for null terminator
std::cout << "Enter the string: ";
std::cin.ignore(); // Ignore the newline character
std::cin.getline(str, length + 1);
std::cout << "Entered string: " << str << std::endl;
delete[] str;
return 0;
}
以上示例展示了C++动态内存的实际使用场景,并给出了相应的源码。这些场景可以根据实际需求进行扩展和修改
原文地址: https://www.cveoy.top/t/topic/hXlb 著作权归作者所有。请勿转载和采集!