2016-09-18 4 views
-1

Следующий код имеет три класса. account, savings (производный), current (производный). Но три функции-члена из базового класса не наследуются. Это ошибка, которую я получаю. Можно ли обойтись без использования виртуальных функцийФункции членов, не получающие наследование в C++

In file included from main.cpp:1:0: 
classes.hpp:96:30: error: no ‘void savingsAccount::deposit()’ member function declared in class ‘savingsAccount’ 
void savingsAccount::deposit() 
          ^
classes.hpp:105:31: error: no ‘void savingsAccount::withdraw()’ member function declared in class ‘savingsAccount’ 
void savingsAccount::withdraw() 
          ^
classes.hpp:130:31: error: no ‘void savingsAccount::display()’ member function declared in class ‘savingsAccount’ 
void savingsAccount:: display() 
          ^
classes.hpp:181:30: error: no ‘void currentAccount::deposit()’ member function declared in class ‘currentAccount’ 
void currentAccount::deposit() 
          ^
classes.hpp:190:31: error: no ‘void currentAccount::withdraw()’ member function declared in class ‘currentAccount’ 
void currentAccount::withdraw() 
          ^
classes.hpp:220:31: error: no ‘void currentAccount::display()’ member function declared in class ‘currentAccount’ 
void currentAccount:: display() 
#include<iostream> 
#include<cstring> 
#define MAX 50 

#ifndef classes_h 
#define classes_h 

using namespace std; 
class account 
{ 
    protected: 
     char name[MAX]; 
     int accountNumber; 
     char type[MAX]; 
     float balance; 
     float minBalance; 
     static int Customers; 
    public: 
     account(); 
     account(char*,int); 

     void deposit();  
     void withdraw(); 
     void display(); 
     int getAccountNumber(); 
     static void numberOfCustomers(); 

}; 

account::account(char* name, int accountNumber) 
{ 
    strcpy(this->name,name); 
    this->accountNumber=accountNumber; 
    //strcpy(this->type,type); 
    this->balance=0; 
    Customers++; 
} 

int account::Customers=0; 
void account ::numberOfCustomers() 
{ 
    cout<<"Total number of customer-------->"<<Customers; 
} 

void account::display() 
{ 

} 

/******************************** 
//Savings Account class 
********************************/ 

class savingsAccount: public account 
{ 
    protected: 
     float minBalance; 
    // float rate; 
    public: 
     savingsAccount(); 
     savingsAccount(char*,int); 
     savingsAccount(account&); //Copy Constructor 
/*  void deposit();  //user 
     void withdraw(); //user 
     void display();  //user 
*/  int getAccountNumber(); 
}; 



savingsAccount::savingsAccount(char* name, int accountNumber):account(name,accountNumber) 
{ 
    minBalance=0; 
    strcpy(type,"savings"); 
} 


savingsAccount::savingsAccount(account& tp):account(tp) 
{ 
    minBalance=0; 
    strcpy(type,"savings"); 
} 



int savingsAccount::getAccountNumber() 
{ 
    return accountNumber; 
}  




void savingsAccount::deposit() 
{ 
    float amount; 
    cout<<"Enter the amount needs to be deposited"<<endl; 
    cin >> amount; 
    balance=balance+amount; 
} 


void savingsAccount::withdraw() 
{ 
    float amount ; 
    if(balance ==0) 
    { 
     cout<<"Account balance is Nil"<<endl; 
     return; 
    } 
    cout<<"Enter the amount yout would like to withdraw"<<endl; 
    while(1) 
    { 
     cin>>amount; 
     if(balance-amount<0) 
     { 
      cout<<"insufficient funds, try some less amount\n"; 

     } 
     else 
     { 
      balance=balance-amount; 
      return ; 
     } 
    } 
} 

void savingsAccount:: display() 
{ 
    cout<<"Account Number"<<accountNumber<<endl; 
    cout<<"Name-->"<<name<<endl; 
    cout<<"Accounttype-->Savings"<<endl; 
    cout<<"Balance-->"<<balance<<endl; 
    cout<<"Minimum Balance -->"<<minBalance; 

} 

/*********************************** 
//Current Account class 
************************************/ 
class currentAccount: public account 
{ 
    protected: 
     float minBalance; 
    public: 
     currentAccount(); 
     currentAccount(char*,int); 
     currentAccount(account&); 
/*  void deposit(); 
     void withdraw(); 
     void display(); 
*/  int getAccountNumber(); 

}; 

/* 
currentAccount::currentAccount(char* name, int accountNumber):account((char*)name,accountNumber,"current account") 
{ 
    minBalance=1000; 
    balance=1000; 
} 
*/ 
currentAccount::currentAccount(char* name, int accountNumber):account(name,accountNumber) 
{ 
    minBalance=0; 
    strcpy(type,"Current"); 
} 


currentAccount::currentAccount(account& tp):account(tp) 
{ 
    minBalance=0; 
    strcpy(type,"Current"); 
} 




void currentAccount::deposit() 
{ 
    float amount; 
    cout<<"Enter the amount needs to be deposited"<<endl; 
    cin >> amount; 
    balance=balance+amount; 
} 


void currentAccount::withdraw() 
{ 
    float amount ; 
    if(balance ==0) 
    { 
     cout<<"Account balance is Nil"<<endl; 
     return; 
    } 
    cout<<"Enter the amount yout would like to withdraw"<<endl; 
    while(1) 
    { 
     cin>>amount; 
     if(balance-amount<0) 
     { 
      cout<<"insufficient funds, try some less amount\n"; 

     } 
     else 
     { 
      balance=balance-amount; 
      return ; 
     } 
    } 
    if(balance-amount<1000) 
    { 
     cout<<"Please keep the balance above minimum balance "; 
    } 

} 

void currentAccount:: display() 
{ 
    cout<<"Account Number"<<accountNumber<<endl; 
    cout<<"Name-->"<<name<<endl; 
    cout<<"Accounttype-->Current Account"<<endl; 
    cout<<"Balance-->"<<balance<<endl; 
    cout<<"Minimum Balance -->"<<minBalance; 

} 

int currentAccount::getAccountNumber() 
{ 
    return accountNumber; 
}  

#endif 

ответ

1

Когда вы

void savingsAccount:: display(){/* rest here */} 

вы сообщаете компилятору реализовать определение функции члена называется savingsAccount::display(). Однако вы не указываете, что у вас есть эта функция-член в объявлениях производного класса. Так как вы перегружены его, вам нужно добавить свою подпись к производным классам, как

class savingsAccount: public account 
{ 
    /* virtual */ void display() /* override */; // probably you want this virtual in the base class 
    // the rest 
}; 

иначе компилятор знает, что существует базовый вариант, то есть account::display(). Поэтому компилятор действительно говорит вам, что нет функции savingsAccount::display(), поскольку у вас есть только account::display(), т. Е. Функция-член базового класса.

Вся ваша проблема может быть упрощена

struct X 
{ 
    void f(); 
}; 

struct Y: X 
{ 
    // void f(); 
}; 

// error if you don't add the signature in Y, 
// there is no Y::f(), only the X::f() inherited part 
void Y::f(){} 

int main(){} 

Live on Coliru

PS: Вы, вероятно, хотите, чтобы эти функции virtual тоже (а также добавить const на те, которые не изменяют свои переменные-члены), поэтому у вас есть правильное переопределение, иначе ваш производный член не будет вести себя так, как вы хотите, когда у вас есть иерархия классов, контролируемая указателем на базу.

PSS: положить

#ifndef classes_h 
#define classes_h 

в самом начале вашего заголовка, прежде чем любой #include.

+0

Нет, вы * не хотите повторно использовать функцию в производном классе для наследования родительского. –

+0

@MarkRansom Вам необходимо, если вы предоставили определение для него в производном классе, но не смогли предоставить прототип, как это сделал OP, см., Например, [Здесь] (http://coliru.stacked-crooked.com/a/40cd6c6e006a7369). Может быть, я не был слишком ясен в своем ответе, я не говорю, что вам нужно переделать, чтобы наследовать, я просто говорю, что ** если ** вы переопределяете, то вам нужна подпись в объявлении производного класса, иначе компилятор ссылается на функцию базового элемента. – vsoftco

+0

Извините, непонятная ошибка с моей стороны. Хороший ответ. –

Смежные вопросы