0

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.

4

2 回答 2

1

Because you're trying to return a DullSmartReference object in this line:

DullSmartReference operator*() const

There is no definition, just a forward declaration.

Therefore,

C2079: The specified identifier is an undefined class, structure, or union.

于 2013-02-13T05:29:30.353 回答
1

该示例中的错误(至少在给出的情况下)是DullSmartReference在定义之前使用的。在 C2079 行上,它试图构造并返回 a 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
}
于 2013-02-13T05:31:46.807 回答