2016-04-12 9 views
0

Was sind die Unterschiede zwischen den folgenden zwei Implementierungen für den Zugriff auf eine private Konstante Klasse Mitglied?Auto-Abzug für Const-Klasse Mitglied

// Auto& (compile ok) 
class Foo { 
    private: 
    const int _foo; 
    public: 
    Foo(const int& in) : _foo(in) {} 
    auto& foo() { return _foo; } 
} 

// Explicit type (compiler error) 
class Foo { 
    private: 
    const int _foo; 
    public: 
    Foo(const int& in) : _foo(in) {} 
    int& foo() { return _foo; } 
} 

Mit auto die Compiler beschweren sich nicht, aber die explizite int Typdeklaration in der Tat gibt Compiler-Fehler (die die Konstantheit zurückzuführen ist). In diesem Fall, was ist auto abgeleitet?

+0

Hinweis: Stellen Sie sicher, dass Sie wissen, was Sie tun w.r.t. Semantik bei der Verwendung von Const-Referenzen. Siehe [int vs const int &] (http://stackoverflow.com/a/4705871/211160). Und beachte, dass es durchaus langsamer sein könnte, als einen int zurückzugeben. – HostileFork

Antwort

4

Da _foo ist vom Typ const int, auto zu const int bezieht. Ändern Sie Ihren 'Explicit type' Code, um const int& zurückzugeben und der Compiler sollte sich nicht mehr beschweren.