简体   繁体   English

在const成员函数中返回C ++引用

[英]Returning a C++ reference in a const member functions

A have a class hierarchy that looks somethign like this: A有一个类层次结构,看起来像这样:

class AbstractDataType { 
public: 
   virtual int getInfo() = 0;
}; 

class DataType: public AbstractDataType { 
public:
   virtual int getInfo() { }; 
};

class Accessor { 
    DataType data; 
public: 
    const AbstractDataType& getData() const { 
        return(data); 
    } 
};

Well, GCC 4.4 reports: 嗯,GCC 4.4报告:

In member function 'const AbstractDataType& Accessor::getData() const': error: invalid initialization of reference of type 'const AbstractDataType&' from expression of type 'const DataType' 在成员函数'const AbstractDataType&Accessor :: getData()const':error:从'const DataType'类型的表达式初始化'const AbstractDataType&'类型的引用无效

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. 您粘贴的代码应该可以工作,并且可以在g ++ 4.4和Visual Studio 2010中工作....除了在类声明之后丢失的分号。

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. 我没有要测试的GCC副本,但问题可能是围绕数据的括号。 The compiler might interpret that as an expression of type DataType, which you couldn't then assign to a reference. 编译器可能会将其解释为DataType类型的表达式,然后您无法将其分配给引用。 Try: 尝试:

return data;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM