Visual Studio - C++:维基教科书中关于重载指针/引用相关运算符的代码无法编译
visual studio - C++: Code from wikibooks on overloading pointer/reference related operators won't compile
我正在尝试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):错误C2027:使用未定义的类型"DullSmartReference"1> e:\projects\bad\example.cpp(13):请参阅"DullSmartReference"的声明1> e:\projects\bad\example.cpp(21):错误C2440:":无法从"T"转换为"DullSmartReference"1> 源或目标的类型不完整
如何修复错误?我正在使用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
}
因为您试图在以下行中返回DullSmartReference
对象:
DullSmartReference operator*() const
没有定义,只是一个正向声明。
因此,
C2079:指定的标识符是未定义的类、结构或并集。
相关文章:
- C++取消引用指针.为什么会发生变化
- 深层复制具有自引用指针的类
- Visual c ++,使用字符串引用/指针调用 dll 函数
- std::unordered_map::提取引用/指针失效
- 为什么在引用指针时将 const 放在 & 符号的左侧有效,而在右侧则无效?
- 区分接受常量参数的函数引用/指针和与函数参数同名的非常量参数
- 如何在 c++ 中使用带有数学运算的引用/指针?
- 了解通过引用传递取消引用指针时C++堆/堆栈分配
- 取消引用指针并立即为其分配变量,导致分段错误
- 如何获取指向类(而不是对象)的引用/指针
- 将类型参数传递给自引用指针
- 我应该如何定义返回指针的函数?(引用指针与指针指针)
- 在析构函数内取消引用指针时出现分段错误
- 来自引用指针的内存泄漏
- 引用指针后面的值
- 无法取消引用指针
- 引用指针调用成员函数
- 未定义的引用指针的变量模板在clang中功能,而不是GCC
- 取消引用指针以创建数组的副本
- 有关启动引用指针的引用的问题