Я пытаюсь следовать книге Вейса о структурах данных и решении проблем с помощью 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: это из-за неправильной реализации или неправильного использования?)
Спасибо:)