This class is A B, C, D are inherited And the objects of B, C, and D Can you tie it up like an array? arr[0]=B object arr[1]=C object arr[2]=D object Is it possible to access the index in this way?
c++표준
I'm going to create an array of pointers for Class A It's upcasting the objects of B, C, and D, so it comes out the way you want it Is it okay to use it like this?
To manage inherited classes from one array, you can convert them to parent types.
#include <iostream>
#include <memory>
struct A {
virtual ~A() {}
virtual void print() { std::cout << "A" << std::endl; }
};
struct B : public A {
void print() { std::cout << "B" << std::endl; }
};
struct C : public A {
void print() { std::cout << "C" << std::endl; }
};
int main() {
A* array[] = {
new B
, , new C
};
for (std::size_t i = 0, size = sizeof(array) / sizeof(array[0]); i < size; ++i)
array[i]->print();
for (std::size_t i = 0, size = sizeof(array) / sizeof(array[0]); i < size; ++i)
delete array[i];
return 0;
}
This method is inconvenient because you have to manage the memory yourself. If you apply the smart pointer here, it is as follows.
#include <iostream>
#include <memory>
struct A {
virtual ~A() {}
virtual void print() { std::cout << "A" << std::endl; }
};
struct B : public A {
void print() { std::cout << "B" << std::endl; }
};
struct C : public A {
void print() { std::cout << "C" << std::endl; }
};
int main() {
std::unique_ptr<A> array[] = {
std::unique_ptr<B>(new B)
, , std::unique_ptr<C>(new C)
};
for (std::size_t i = 0, size = sizeof(array) / sizeof(array[0]); i < size; ++i)
array[i]->print();
return 0;
}
© 2024 OneMinuteCode. All rights reserved.