我正在收到此错误,并且不确定如何解决它,#include "stdafx.h"

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

class Puzzle {
public:
virtual bool action(char [][8], int, int) = 0;
virtual void print_solution(char [][8], int) = 0;
};

class Queen8: public Puzzle {
public:
bool action(char Q[][8], int row, int col) {
    for (int r = 0; r < row; r++) {
        if (Q[r][col] == '1') {
            return false;
        }
    }
    for (int r = row, c = col; r >= 0 && c >= 0; r--, c--) {
        if (Q[r][c] == '1') {
            return false;
        }
    }
    for (int r = row, c = col; r >= 0 && c < 8; r--, c++) {
        if (Q[r][c] == '1') {
            return false;
        }
        else {
            return true;
        }
    }
  }

  void print_solution(char Q[][8], int row) {
    if (row == 8)
    {
        for (int r = 0; r < 8; r++) {
            for (int c = 0; c < 8; c++)
                cout << Q[r][c] << " ";
            cout << endl;
        }
        cout << endl;
        return;
    }
    for (int c = 0; c < 8; c++) {
        if (action(Q, row, c)) {
            Q[row][c] = '1';
            print_solution(Q, row + 1);
            Q[row][c] = '0';
        }
    }
}
};



int main() {
Puzzle Queen8;
char Q[8][8];
for (int r = 0; r < 8; r++) {
    for (int c = 0; c < 8; c++) {
        Q[r][c] = '0';
    }
}
Queen8.print_solution(Q, 0);

}


确切的错误是:


  c:\ users \ delta \ onedrive \ documents \ visual studio
  2013 \ projects \ consoleapplication46 \ consoleapplication46 \ consoleapplication46.cpp(60):
  错误C2259:“拼图”:无法实例化抽象类
  
  1>由于以下成员:
  
  1>'bool Puzzle :: action(char [] [8],int,int)':是抽象的
  
  1> c:\ users \ delta \ onedrive \ documents \ visual studio
  2013 \ projects \ consoleapplication46 \ consoleapplication46 \ consoleapplication46.cpp(9)
  :请参阅“ Puzzle :: action”的声明
  
  1>'void拼图:: print_solution(char [] [8],int)':是
  抽象
  
  1> c:\ users \ delta \ onedrive \ documents \ visual studio
  2013 \ projects \ consoleapplication46 \ consoleapplication46 \ consoleapplication46.cpp(10)
  :请参阅“ Puzzle :: print_solution”的声明

最佳答案

main()函数中,您要实例化Puzzle类,而不是Queen8类:

Puzzle Queen8;


您应该实例化Queen8

Queen8 q;
...
q.print_solution(Q, 0);


除此之外,覆盖虚拟函数(C ++ 11及更高版本)时,应始终使用override关键字。这将告诉编译器您的意图,并且在您遗漏任何内容时会给您更好的警告和错误。因此,在Queen8类中,您应该具有:

bool action(char Q[][8], int row, int col) override {
    ...
}

void print_solution(char Q[][8], int row) override {
    ...
}

关于c++ - 抽象类错误,请参见“”的声明是抽象的,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52921949/

10-13 08:10