Return Custom Data Types
In C++, you can return custom structures and classes from functions. When you return an instance of a struct or class from a function, you essentially return a copy of the object ( the same as returning simple data types).
This allows you to encapsulate related data and behavior within a single structure or class instance, pass it around between functions, or use it in different parts of your program.
To return a structure/class, you must use the structure/class name as a type specifier in the function signature.
main.cpp
12345678910111213141516171819202122#include <iostream> // Define a custom structure called Person struct Person { std::string name; int age; }; // Function that returns a Person object Person createPerson(const std::string name, const int age) { return Person { name, age }; } int main() { // Call the function to create a Person object Person person1 = createPerson("Alice", 30); // Access and print the attributes of the returned Person object std::cout << "Name: " << person1.name << std::endl; std::cout << "Age: " << person1.age << std::endl; }
Дякуємо за ваш відгук!
Запитати АІ
Запитати АІ
Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат
Запитайте мені питання про цей предмет
Сумаризуйте цей розділ
Покажіть реальні приклади
Awesome!
Completion rate improved to 5
Return Custom Data Types
Свайпніть щоб показати меню
In C++, you can return custom structures and classes from functions. When you return an instance of a struct or class from a function, you essentially return a copy of the object ( the same as returning simple data types).
This allows you to encapsulate related data and behavior within a single structure or class instance, pass it around between functions, or use it in different parts of your program.
To return a structure/class, you must use the structure/class name as a type specifier in the function signature.
main.cpp
12345678910111213141516171819202122#include <iostream> // Define a custom structure called Person struct Person { std::string name; int age; }; // Function that returns a Person object Person createPerson(const std::string name, const int age) { return Person { name, age }; } int main() { // Call the function to create a Person object Person person1 = createPerson("Alice", 30); // Access and print the attributes of the returned Person object std::cout << "Name: " << person1.name << std::endl; std::cout << "Age: " << person1.age << std::endl; }
Дякуємо за ваш відгук!