简体   繁体   中英

C++: inherit base class Method

I have this simple code:

class A {
public:
   string toString() const { return "A"; }
};

class B : public A {
public:
   string toString() const { // some code here }
};

I want toString() in class B will inherit from class A and take some extra values. In this example, will be: "AB" (A: from class A, and B: extra string).

This is easy in Java, but I don't know how to do in C++. My first idea is take string from toString() in class A and append additional string. So, to take this: I use: static_cast<A>(const_cast(this))->toString() but it won't work :(

Please help me. Thanks :)

class A {
public:
   string toString() const { return "A"; }
};

class B : public A {
public:
   string toString() const { return A::toString() + "B"; }
};

In MS implementation (on Windows) you can do __super::toString() instead, but that's a non-portable MS extension.

string B::toString() const {
   string result = A::toString();   // calls the member method in A
                                    // on the current object
   result += "B";
   return result;
}

The qualification on the call to the function determines what function override (if the function is polymorphic) will be called, so it ensures that dynamic dispatch does not dispatch to B::toString() again. The main difference from Java is that because C++ allows for multiple inheritance, you have to name the base A:: rather than just calling super .

First of all you probably want the toString to be virtual. Second, to accomplish what you want, you can do something like this in B::toString:

class B : public A
{
    ...
    virtual string toString() const
    {
        string s = A::toString();
        s += "B";
        return s;
    }
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM