Returning a C++ reference in a const member functions
A have a class hierarchy that looks somethign like this:
class AbstractDataType {
public:
virtual int getInfo() = 0;
};
class DataType: public AbstractDataType {
public:
virtual int getInfo() { };
};
class Accessor {
Data开发者_如何学编程Type data;
public:
const AbstractDataType& getData() const {
return(data);
}
};
Well, GCC 4.4 reports:
In member function ‘const AbstractDataType& Accessor::getData() const’: error: invalid initialization of reference of type ‘const AbstractDataType&’ from expression of type ‘const DataType’
Where am I going wrong - is this a case where I MUST use a pointer?
[edit - fixed semi-colons]
No you do not need to use a pointer. You can use a reference or a pointer equally in this case.
The code you pasted should work and does work in g++ 4.4 and Visual Studio 2010.... other than the missing semicolons after the class declarations.
I'm guessing maybe your code here doesn't match exactly the code you are compiling.
In particular did you accidentally do this in code?
class DataType /*: public AbstractDataType*/ {
public:
virtual int getInfo() { };
};
I don't have a copy of GCC to test, but the problem might be the parenthesis around data. The compiler might interpret that as an expression of type DataType, which you couldn't then assign to a reference. Try:
return data;
精彩评论