【发布时间】:2014-01-07 01:00:44
【问题描述】:
我有“无法分配抽象类型的对象”错误。
当我创建一个对象Be(继承自抽象类Ae)并将它传递给采用const Ae& 的方法时,我得到了它。我认为作为参考传递时应该不是问题。错误说:error: allocating an object of abstract class type Be。
程序的逻辑如下:
//A.hpp
struct A : public std::exception { //Exception class
class Ae { //Error message class
virtual const char* message() const = 0;
inline operator const char*() const {
return message();
}
};
// fields describing where the error occurred in file input
int a, b, c, d;
// string reporting what happened
const char* msg;
A( const Ae& e, int a, int b, int c, int d ) : a(a), b(b), c(c), d(d), msg(e)
{}
const char* what() const throw() { /* printing some nice report */ }
~A() throw () {}
};
//B.hpp
struct B : public A {
B( const Ae& e, int a, int b, int c, int d ) : A( e,a,b,c,d )
{}
struct Be : public Ae { //particular error having relevant class name e.g. IncorrectInput
const char* message() const {
return "Some error description";
}
}; // more of alikes
};
//AUser.hpp
struct AUser { // some module that will be throwing A
int a, b, c, d;
A Exception( const Ae& e ) {
return A( e, a, b, c, d );
}
};
//BUser.hpp
struct BUser : public AUser {
void fun() { // any method
// (...) does sth
if ( goeswrong )
throw Exception( B::Be() );
}
};
我的代码有什么问题?
为了阐明此类结构的目标 - AUser 是 CsvFile,BUser 是 ParticularCsvFile(使用方法识别哪个字段包含哪种数据类型),A 是 CsvFileExceotion,B 是 ParticularFileException,Ae 是 ErrorCode,Be 是例如 ErrorWhenReadingPricesCell
包含throw Exception( B::Be() ); 的行弹出错误,另外声明note: unimplemented pure virtual method 'message' in 'Be'
public: virtual const char* message() const = 0;
编辑
根据要求,exact g++ -Wall -pedantic -Wextra 如下所示。 请注意,我简化了上面的代码并更改了名称: BUser == DividendsFile, B == DividendsFileReadingException, Be == UnexpectedStockDividend, AUser == CsvFile, A == CsvFileReadingException, Be == ErrorCode
quotreader2.cpp:18:5: warning: unused parameter ‘argc’ [-Wunused-parameter]
Input/DividendsFile.cpp: In member function ‘int DividendsFile::getStockDividend()’:
Input/DividendsFile.cpp:28:85: error: cannot allocate an object of abstract type ‘DividendsFileReadingException::UnexpectedStockDividend’
In file included from Input/DividendsFile.cpp:3:0:
Input/Exceptions/DividendsFileReadingException.hpp:28:12: note: because the following virtual functions are pure within ‘DividendsFileReadingException::UnexpectedStockDividend’:
In file included from Input/CsvFile.hpp:4:0,
from Input/DividendsFile.hpp:4,
from Input/DividendsFile.cpp:2:
Input/Exceptions/CsvFileReadingException.hpp:17:37: note: virtual const char* CsvFileReadingException::ErrorCode::message() const
make: *** [bin/test.bin] Error 1
【问题讨论】:
-
哪一行是错误(我看过一次,没看出来)
-
@AlecTeal 我更新了该信息的问题。见底部。
-
Be中的virtual关键字忘记了吗?
-
你不能只在代码中添加
:public Ae而不更新你得到的错误,你现在太残忍了 -
我怀疑 OP 在代码中有错字,他忘记在此处转录了...(但添加新的:/)
标签: c++ inheritance abstract-class virtual-functions