为自定义SmartPointer重载“*”运算符

时间:2013-11-19 20:33:58

标签: visual-c++ operator-overloading smart-pointers

我试图通过重载*运算符直接访问指针类中的整数,但似乎VC ++ 10不允许它。请帮助:

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
int MAX7 = 10;

struct node{
    int value;
    node *next;
};
struct node *head = NULL;
struct node *current = NULL;
int count = 0;

class SmartPointer{
public:
    SmartPointer(){
    }
    int push(int i){
        if(count == MAX7)   return 0;

        if(head == NULL){
            head = new node();
            current = head;
            head -> next = NULL;
            head -> value = i;
            count = 1;
        }
        else{
            struct node *ptr = head;
            while(ptr->next != NULL)    ptr = ptr->next;
            ptr->next = new node;
            ptr = ptr->next;
            ptr->next = NULL;
            ptr->value = i;
            count++;
        }
        return 1;
    }
    void Display(){
        node *ptr = head;
        while(ptr != NULL){
            cout << ptr->value << "(" << ptr << ")";
            if( ptr == current )
                cout << "*";
            cout << ", ";
            ptr = ptr->next;
        } 
    }

    int operator *(){
        if(current == NULL) return -1;
        struct node *ptr = current;
        return ptr->value;
    }
};

int main(){
    SmartPointer *sp;
    sp = new SmartPointer();
    sp->push(99);
    for(int i=100; i<120; i++){
        if(sp->push(i))
            cout << "\nPushing ("<<i<<"): Successful!";
        else
            cout << "\nPushing ("<<i<<"): Failed!";
    }
    cout << "\n";
    sp->Display();

    int i = *sp;

    getch();
    return 0;
}

错误# 1&gt; test7.cpp(71):错误C2440:'初始化':无法从'SmartPointer'转换为'int' 1 GT;没有可用于执行此转换的用户定义转换运算符,或者无法调用运算符

2 个答案:

答案 0 :(得分:1)

sp不是智能指针 - 它是指向SmartPointer类的普通旧哑指针。 *sp使用内置解除引用运算符,生成SmartPointer类型的左值。它不会调用SmartPointer::operator*() - 为此,您需要编写**sp(两颗星)。

为什么要在堆上分配SmartPointer实例并不清楚。这是一个不寻常的事情(也是,你泄漏它)。

我很确定你会好起来的
SmartPointer sp;
sp.push(99);

等等。

答案 1 :(得分:0)

简短回答:

int i = **sp;

您不应该使用new分配对象。你的代码看起来像java。在C ++中,您必须删除使用new分配的所有内容。在C ++中,您可以编写:

SmartPointer sp;
sp.push(99);
int i = *sp;
相关问题