简体   繁体   中英

C++ inherited functions not being found

I new in C++ and I have difficulty to understand how to get my function with inheritance. I have a Class that is link to another with inheritance, everything work except:

I cannot reach my superclass function.

Here's my class header : Point.h (I don't include the .cpp):

#ifndef Point_H
#define Point_H
#include <iostream>
class Point{
  public:
         Point(); 
         void set_values (int , int);
         void set_values (int , int , int );
         void affichervaleurs();
         int getX() const { return x; }
         int getY() const { return y; }
  private:
         int x ;
         int y ;
         int z ;
  };
#endif

Now My other class that try to access the function getX from Point.h : The header : Carre.h

#ifndef Carre_H
#define Carre_H
#include "Point.h"

class Carre : public Point{      
  public:
         Carre();
         //Carre(int a , int b);
         //Carre(int a, int b):Point(a,b) {};
         //Carre(int a, int b, int c):Point(a, b, c) {};
         //const Point &pp;
         int Aire (){
         };
         void affichercar(){
                       };

  };
#endif

Carre.cpp

#include <iostream>
using namespace std;
#include "Carre.h"
#include "Point.h"

Carre::Carre():Point(){
  };
         //Carre::Carre(int a, int b);
         //const &pp;
         int Aire (){
              return (getX() * getY()); 
         };
         void affichercar(){
         //cout << "Coordonnees X:" << x  << endl;
                       };

It says that my GetX() is undeclared in my Carre.cpp . Like I said I'm new in C++ Does someone know what I'm missing to make that code work. ?

Your definition is missing the class scope, which makes it a free function instead of a member.

It should be

int Carre::Aire (){
    return getX() * getY(); 
};

In the .cpp file for Carre, the functions Aire and affichercar are global. Presumably you intended:

int Carre::Aire(){
          return (getX() * getY()); 
     };

For example.

Declaring function outside class body requires a class specifier:

int Carre::Aire () {
    return (getX() * getY()); 
};

void Carre::affichercar() {
    //...
}

Otherwise

int Aire () {
    return (getX() * getY()); 
};

is just another function in global namespace that can exists simutaneously to Carre::Aire() .

This is because you are not implementing the Aire function as being part of the Carre class.

Try changing

int Aire (){

to

int Carre::Aire (){

Also, you already have an implementation of the Aire method in the header file. You should either implement the function inline in the header file, or in the .cpp file, but not both. This also applies to your affichercar method.

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