реализация постоянной ссылки в c ++ (по книге Вайса) - PullRequest
0 голосов
/ 02 апреля 2012

Я пытаюсь следовать книге Вейса о структурах данных и решении проблем с помощью c ++.

Я пытаюсь работать с постоянным ссылочным классом, как написано в книге, но он продолжает давать мне компиляциюошибки.

Обновление: я изменил код, но некоторые старые ошибки остаются.

//Class that wraps a constant reference variable.
//useful for return values from a container find method.
#include <iostream>
using namespace std;

class NullPointerException: public exception{

};

template <class Object>
class Cref{
   public:
    Cref() : obj(NULL){}
    explicit Cref( const Object & x): obj( &x){ }

    const Object & get() const{
        if(isNull()){
            throw NullPointerException( );
        }
        else{
            return *obj;
        }
    }
    bool isNull( ) const{
        return obj == NULL;
    }

private:
    const Object* obj; //stores a pointer...

};

// Пример использования:

class TestClass {int test;

public:
    TestClass():test(10){}

    int& get(bool valid){
        if(valid){
            Cref<int> retv(test);
            return retv;
        }
        else{
            Cref<int> retv;
            return retv;

        }
    }

};

int main( ){
    TestClass temp;
    try{
        Cref<int> test = temp.get(true);
        Cref<int> test2 = temp.get(false);
    }
    catch(exception& e){
        cout<<"NULL pointer exception occurred"<<endl;
    }

}

3_ConstRef.cpp: In member function ‘int& TestClass::get(bool)’:
3_ConstRef.cpp:44:12: error: invalid initialization of reference of type ‘int&’ from expression of type ‘Cref<int>’
3_ConstRef.cpp:48:12: error: invalid initialization of reference of type ‘int&’ from expression of type ‘Cref<int>’
3_ConstRef.cpp: In function ‘int main()’:
3_ConstRef.cpp:59:33: error: conversion from ‘int’ to non-scalar type ‘Cref<int>’ requested
3_ConstRef.cpp:60:35: error: conversion from ‘int’ to non-scalar type ‘Cref<int>’ request

ed

Как решить эти проблемы?(ps: это из-за неправильной реализации или неправильного использования?)

Спасибо:)

1 Ответ

0 голосов
/ 02 апреля 2012

3_ConstRef.cpp: In member function ‘const Object& Cref<Object>::get() const’: 3_ConstRef.cpp:15:33: error: there are no arguments to ‘NullPointerException’ that depend on a template parameter, so a declaration of ‘NullPointerException’ must be available [-fpermissive]

NullpointerException не зависит от аргументов вашего шаблона, поэтому должно быть глобальное объявление функции. Кажется, вы пропустили несколько заголовков. Смотрите эту ссылку для более подробной информации:

http://gcc.gnu.org/onlinedocs/gcc/Name-lookup.html

3_ConstRef.cpp: In member function ‘int& TestClass::get(bool)’: 3_ConstRef.cpp:41:12: error: invalid initialization of reference of type ‘int&’ from expression of type ‘Cref<int>’ 3_ConstRef.cpp:45:12: error: invalid initialization of reference of type ‘int&’ from expression of type ‘Cref<int>’

В TestClass::get() вы пытаетесь вернуть объект типа Cref<int>, но тип возврата - int&. Не рекомендуется возвращать возвращаемую ссылку на локальный объект, см. Этот вопрос SO:

Ссылка на функцию возврата C ++

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...