Guest User

Untitled

a guest
Jul 20th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1. code:
  2.  
  3. //Class that wraps a constant reference variable.
  4. //useful for return values from a container find method.
  5. #include <iostream>
  6. using namespace std;
  7.  
  8.  
  9. template <class Object>
  10. class Cref{
  11.     public:
  12.         Cref() : obj(NULL){}
  13.         explicit Cref( const Object & x): obj( &x){ }
  14.  
  15.         const Object & get() const{
  16.             if(isNull()){
  17.                 throw NullPointerException( );
  18.             }
  19.             else{
  20.                 return *obj;
  21.             }
  22.         }
  23.         bool isNull( ) const{
  24.             return obj == NULL;
  25.         }
  26.  
  27.     private:
  28.         const Object* obj; //stores a pointer...
  29. };
  30.  
  31. //Usage example:
  32.  
  33. class TestClass{
  34.     int test;
  35.    
  36.  
  37.     public:
  38.         TestClass():test(10){}
  39.  
  40.         int& get(bool valid){
  41.             if(valid){
  42.                 Cref<int> retv(test);
  43.                 return retv;
  44.             }
  45.             else{
  46.                 Cref<int> retv;
  47.                 return retv;
  48.  
  49.             }
  50.         }
  51. };
  52.  
  53.        
  54.  
  55. int main( ){
  56.     TestClass temp;
  57.     try{
  58.         Cref<int> test = temp.get(true);
  59.         Cref<int> test2 = temp.get(false);
  60.     }
  61.     catch(exception& e){
  62.         cout<<"NULL pointer exception occurred"<<endl;
  63.     }
  64.  
  65. }
  66.  
  67. The error message:
  68.  
  69. 3_ConstRef.cpp: In member function ‘const Object& Cref<Object>::get() const:
  70. 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]
  71. 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)
  72. 3_ConstRef.cpp: In member function ‘int& TestClass::get(bool):
  73. 3_ConstRef.cpp:41:12: error: invalid initialization of reference of type ‘int&’ from expression of type ‘Cref<int>
  74. 3_ConstRef.cpp:45:12: error: invalid initialization of reference of type ‘int&’ from expression of type ‘Cref<int>
  75. 3_ConstRef.cpp: In function ‘int main():
  76. 3_ConstRef.cpp:56:33: error: conversion from ‘int’ to non-scalar type ‘Cref<int>’ requested
  77. 3_ConstRef.cpp:57:35: error: conversion from ‘int’ to non-scalar type ‘Cref<int>’ requested
Add Comment
Please, Sign In to add comment