I'm trying a piece of example code from wikibooks (http://en.wikibooks.org/wiki/C%2B%2B_Programming/Operators/Operator_Overloading), but it won't compile in Visual Studio. The code is about overloading address of, reference, and pointer operators (operator&()
, operator*()
and operator->()
):
//file example.cpp
#include "stdafx.h"
#include <iostream>
class T {
public:
const void memberFunction() const {
std::cout << "Hello!\n";
}
};
// forward declaration
class DullSmartReference;
class DullSmartPointer {
private:
T *m_ptr;
public:
DullSmartPointer(T *rhs) : m_ptr(rhs) {};
DullSmartReference operator*() const {
return DullSmartReference(*m_ptr);
}
T *operator->() const {
return m_ptr;
}
};
class DullSmartReference {
private:
T *m_ptr;
public:
DullSmartReference (T &rhs) : m_ptr(&rhs) {}
DullSmartPointer operator&() const { // error C2027: use of undefined type 'DullSmartReference'
return DullSmartPointer(m_ptr);
}
// conversion operator
operator T() { return *m_ptr; }
};
int _tmain(int argc, _TCHAR* argv[])
{
DullSmartPointer dsp(new T);
dsp->memberFunction(); // calls T::memberFunction
T t;
DullSmartReference dsr(t);
dsp = &dsr;
t = dsr; // calls the conversion operator
std::cin.get();
return 0;
}
Visual studio always reports Compiler Error C2079. The error message is
1>e:\projects\bad\example.cpp(20): error C2027: use of undefined type 'DullSmartReference' 1> e:\projects\bad\example.cpp(13) : see declaration of 'DullSmartReference' 1>e:\projects\bad\example.cpp(21): error C2440: '' : cannot convert from 'T' to 'DullSmartReference' 1> Source or target has incomplete type
How can I fix the errors? I'm using VS 2010, but I don't think the version matters. Thanks!
Update: 1. I updated the code and complete error message.