Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

c++ - Access default declared content from inherited class

I'm trying to make an inherited class access the self class default content. The code is below (Note that array declared isn't the same size between parent and child class)

#include <iostream>

class A {
    public:
        int number[2] = {1,2};
        A(){};
        void show() {std::cout << "Number: " << number[0] << ", " << number[1] << "
"; };
};

class B : public A {
    public:
        int number[3] = {5,6,7};
        B() {};
        // With this code below it works but I don't want to code the same function on every child class
        //void show() {std::cout << "Number: " << number[0] << ", " << number[1] << "
"; };
};

int main() {
    A obj_a;
    obj_a.show();
    B obj_b;
    obj_b.show();
}

Which outputs this:

Number: 1, 2
Number: 1, 2

Expected output should be:

Number: 1, 2
Number: 5, 6

Anyone can help?

Note: The code should be used on arduino, I used std::cout just for sharing to you.

EDIT: I want to make an array of objects so it can be easily changed the size, and in other parts of the code, I can simply for loop of the array and do whatever is needed. Also the purpose for subclasses is because I have different "numbers" and his sizes. For example, imagine a vehicle which is the super class, that has 2 child classes named "auto" and "moto", auto has int wheels[4] = {...} and moto int wheels[2] = {...}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A::number and B::number are two completely independent class members, that have nothing to do with each other.

A::show() only knows about members of A, and only knows about A::number. It doesn't know anything about B even if it's a superclass of an instance of B.

Your C++ textbook will explain what virtual functions are, and how to use them. The simplest solution is to add a virtual method in A, let's call it get_number, that returns an int *, and the get_number function simply returns number:

class A {

   // ...

   virtual int *get_number()
   {
        return number;
   }
};

In B the virtual function gets overridden, and it returns a pointer to its own class's number.

class B {

   // ...

   int *get_number() override
   {
        return number;
   }
};

Then, your show() method calls get_number() to get a pointer to the appropriate array. See your C++ textbook for a complete discussion of virtual class methods.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...