我正在嘗試撰寫國際象棋程式。我要創建的是虛擬父類工具,以及每種和平型別的子類。這是我寫的 4 個檔案:
工具.h
#pragma once
#include <iostream>
using namespace std;
class Tool
{
protected:
string type;
int row;
int colum;
int player;
public:
Tool(int row, int col, int player = 0);
string getType();
int getRow();
int getColum();
int getPlayer();
bool isLegitimateMove(int row, int col);
void move(int row, int col);
};
工具.cpp
#include "Tool.h"
Tool::Tool(int x, int y , int p) :
type("")
{
row = x;
colum = y;
player = p;
}
int Tool::getColum() {
return colum;
}
int Tool::getRow() {
return row;
}
int Tool::getPlayer() {
return player;
}
string Tool::getType() {
return type;
}
void Tool::move(int newRow, int newColum) {
row = newRow;
colum = newColum;
}
國王.h
#pragma once
#include "Tool.h"
class King : public Tool {
};
國王.cpp
#include "King.h"
#include <cstdlib>
bool King::isLegitimateMove(int a, int b) {
return (abs(a - row) <= 1) and (abs(b - colum) <= 1);
}
但是 VS 不讓 King 從 Tool 繼承并撰寫下一個錯誤:
E0298 inherited member is not allowed (King.cpp Line 4)
C2509 'isLegitimateMove': member function not declared in 'King' (King.cpp Line 4)
你能幫我修復這段代碼嗎?我已經閱讀了這本手冊https://www.geeksforgeeks.org/inheritance-in-c/ 但它對我沒有幫助。
uj5u.com熱心網友回復:
問題是,為了為類的成員函式提供類外定義,該成員函式的宣告必須存在于類中。而且由于派生類中沒有這樣的宣告King,我們不能像你那樣定義它。
因此,要解決這個問題,請在派生類中為成員函式添加宣告King:
class King : public Tool {
bool isLegitimateMove(int row, int col); //declaration added
};
此外,您可能希望通過在基類中宣告它時添加關鍵字來創建isLegitimateMove一個虛擬成員函式。virtual
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/528246.html
標籤:C 遗产
上一篇:如何使彈出視頻回應于移動設備
