[英]C++ Overloading the function operator and inheritance, can't use it properly within a subclass function
我是一名學生,這是我用c ++的第一學期,因此對於任何草率的代碼,我都表示歉意。 我需要有關操作重載的幫助,尤其是函數operator()和繼承。 我已經在網上兜售信息,但無濟於事。 我正在嘗試做的事; 我在類RandomInt中重載了函數operation(),現在我試圖從繼承的類BankAcct中訪問它,特別是我試圖從一個公共函數中訪問它。 我刪除了所有注釋以使代碼更短。 向下滾動至bankacct.cpp以查看需要更正的代碼。 我有一個工作的randomInt.cpp和randomInt.h文件
randomInt.h
#include <iostream>
#include <cstdlib>
#include <sstream>
using namespace std;
#ifndef RANDOMINT_H
#define RANDOMINT_H
class RandomInt {
public:
RandomInt();
RandomInt(int ia, int ib);
int get_random_int();
int operator()();
int operator()(int num_b);
int operator()(int num_a, int num_b);
private:
int a , b, randomInt;
};
#endif
和randomInt.cpp
#include "randomInt.h"
using namespace std;
RandomInt::RandomInt(){
a = 1000;
b = 9999;
randomInt = 0;
}
RandomInt::RandomInt(int ia, int ib){
a = ia;
b = ib;
randomInt = 0;
}
int RandomInt::get_random_int(){
return randomInt;
}
int RandomInt::operator()(){
return randomInt = a + rand() % (b - a + 1);
}
int RandomInt::operator()(int num_b){
return randomInt = a + rand() % (num_b - a + 1);
}
int RandomInt::operator()(int num_a, int num_b){
return randomInt = num_a + rand() % (num_b - num_a + 1);
}
現在,我自己就已經實現了這些功能。
現在,下面的代碼正在編譯,並且按照我想要的方式工作,但是我敢肯定有更好的方法。
#include <iostream>
#include <sstream>
#include <string>
#include "randomInt.h"
using namespace std;
#ifndef BANKACCT_H
#define BANKACCT_H
class BankAcct : public RandomInt {
public:
BankAcct();
string get_pinCode();
string get_BSB();
string int_to_string(int integer);
private:
string BSB;
string pinCode;
void set_pinCode();
};
#endif
和bankacct.cpp文件
#include "bankacct.h"
#include "randomInt.h"
using namespace std;
BankAcct::BankAcct(){
BSB = "324-001";
}
string BankAcct::get_pinCode(){
set_pinCode();
return pinCode;
}
string BankAcct::get_BSB(){
return BSB;
}
string BankAcct::int_to_string(int integer) {
stringstream out;
out << integer;
return out.str();
}
void BankAcct::set_pinCode(){
// THIS IS WHERE I BELIEVE THE ISSUE IS.
RandomInt R;
int code = R();
pinCode = int_to_string(code);
}
我已經初始化了一個類對象,以使其能夠工作,就像我過去使用繼承的分配那樣,我可以簡單地調用繼承的類函數。 有人能幫助我嗎? 或提供正確的語法。
然后,我按以下方式進行檢查。
#include <iostream>
#include <ctime>
#include "bankacct.h"
#include "randomInt.h"
using namespace std;
int main() {
srand(time(0));
BankAcct newAcct;
for (int i = 0; i < 10; i++){
cout << newAcct.get_pinCode() << endl;
cout << newAcct.get_BSB() << endl;
}
return 0;
}
記住它按預期工作,但是我不明白為什么我必須像以前那樣制作一個類對象。
請提供任何幫助。
除了對BankAcct
不必要地繼承RandomInt
BankAcct
,使用類也沒有錯。 您可以通過簡單地使用class BankAcct {
來刪除繼承。
您的代碼工作正常,並且已聲明類RandomInt
以便輕松設置randomizer變量。
關於繼承,您說您在訪問基類的函數之前已經使用了函數名。 在繼承的類的函數內,您只能對函數執行此操作,而不能對運算符進行操作,因為您不能簡單地調用int code = ();
因為那沒有任何意義。
當繼承的類在基類上擴展時,繼承最有用。 我想建議此鏈接指示繼承的優勢。 在你的榜樣, BankAcct
簡單的使用RandomInt
,而不是被延期RandomInt
,因此不需要繼承。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.