Visual Studio - C++:维基教科书中关于重载指针/引用相关运算符的代码无法编译

visual studio - C++: Code from wikibooks on overloading pointer/reference related operators won't compile

本文关键字:引用 指针 运算符 编译 代码 重载 C++ Studio 于重载 教科书 Visual      更新时间:2023-10-16

我正在尝试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:指定的标识符是未定义的类、结构或并集。