Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- code:
- //Class that wraps a constant reference variable.
- //useful for return values from a container find method.
- #include <iostream>
- using namespace std;
- 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...
- };
- //Usage example:
- 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;
- }
- }
- The error message:
- 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]
- 3_ConstRef.cpp:15:33: note: (if you use ‘-fpermissive’, G++ will accept your code, but allowing the use of an undeclared name is deprecated)
- 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>’
- 3_ConstRef.cpp: In function ‘int main()’:
- 3_ConstRef.cpp:56:33: error: conversion from ‘int’ to non-scalar type ‘Cref<int>’ requested
- 3_ConstRef.cpp:57:35: error: conversion from ‘int’ to non-scalar type ‘Cref<int>’ requested
Add Comment
Please, Sign In to add comment