我正在尝试 wikibooks ( http://en.wikibooks.org/wiki/C%2B%2B_Programming/Operators/Operator_Overloading ) 中的一段示例代码,但它无法在 Visual Studio 中编译。该代码是关于重载地址、引用和指针运算符(operator&()
、operator*()
和 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 总是报告编译器错误 C2079。错误信息是
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
如何修复错误?我正在使用 VS 2010,但我认为版本不重要。谢谢!
更新: 1. 我更新了代码并完成了错误信息。
最佳答案
该示例中的错误(至少在给定的情况下)是 DullSmartReference
在定义之前被使用。在 C2079 行,它试图构造并返回一个 DullSmartReference
,如果没有它的定义,这是不可能的。要解决此问题,该部分代码应为:
// forward declaration
class DullSmartReference;
class DullSmartPointer {
private:
T *m_ptr;
public:
DullSmartPointer(T *rhs) : m_ptr(rhs) {};
DullSmartReference operator*() const; // DullSmartReference not used yet
T *operator->() const {
return m_ptr;
}
};
// DullSmartReference definition goes here
DullSmartReference DullSmartPointer::operator*() const {
return DullSmartReference(*m_ptr); // OK; we have the definition by now
}
关于C++:wikibook 中关于重载指针/引用相关运算符的代码无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14846889/