简体   繁体   中英

Virtual function declaration and inheritance in C++

I have a program that is trying to create derived classes from a basic abstract class. My .h file is here.

#ifndef SHIP_H
#define SHIP_H
class Ship
{
  public:
    virtual ~Ship(void) {}
    virtual const char *name(void) const = 0;
    virtual int size(void) const = 0;
    int getX(int i) const;
    int getY(int i) const;
    void print(void) const;
    bool includes(int x, int y);
int level(void) const;
void decreaseLevel(void);
static Ship *makeShip(char ch, int x1, int y1, int x2, int y2);
  protected:
    void setPos(int a1, int b1, int a2, int b2);
    int lev;
  private:
    bool checkConfig(int x1, int y1, int x2, int y2);
    int x1,y1,x2,y2;
    };

class AircraftCarrier : public Ship
{
  public:
   AircraftCarrier(int x1, int y1, int x2, int y2);
   virtual const char *name(void) const;
   virtual int size(void) const;
};

and in my Ship.cpp file I have:

const char *name (void) {

    const char * ret = "AircraftCarrier"; 
    return ret;
}

However this isn't declared in the specific scope of my derived class AircraftCarrier. However whenever I add the

const char AircraftCarrier :: *name {...}

I get an error:

Ship.cpp:46:9: error: cannot convert 'const char*' to 'const char AircraftCarrier::*' in return return ret;

您要在Ship.cpp中声明的函数的名称为AircraftCarrier :: name(),并且该函数应根据头文件中的声明返回const char *。

const char *AircraftCarrier::name() {...}

This definition:

const char *AircraftCarrier::name() {...}

is incorrect. Try use this, and you'll get the "member not found" compile error. Your declaration and definition must have an identical prototype. So if you're written the:

virtual const char *name(void) const;
        ^^^^^                  ^^^^^

declaration in .h, then your definition in .cpp must completely match the declaration in your proto. The right definition is:

const char* AircraftCarrier::name() const 
{
    // your complex code here
}

It should be:

const char* AircraftCarrier :: name {...}

The * is part of the return type specification, not the functions name.

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