Visual c++ 超载“*&引用;自定义智能指针的运算符

Visual c++ 超载“*&引用;自定义智能指针的运算符,visual-c++,operator-overloading,smart-pointers,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 = NUL

我试图通过重载*运算符直接从指针类访问整数,但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;
}
#包括“stdafx.h”
#包括
#包括
使用名称空间std;
int MAX7=10;
结构节点{
int值;
节点*下一步;
};
结构节点*head=NULL;
结构节点*current=NULL;
整数计数=0;
类智能指针{
公众:
智能指针(){
}
int推送(int i){
if(count==MAX7)返回0;
if(head==NULL){
头=新节点();
电流=水头;
head->next=NULL;
头->值=i;
计数=1;
}
否则{
结构节点*ptr=头部;
而(ptr->next!=NULL)ptr=ptr->next;
ptr->next=新节点;
ptr=ptr->next;
ptr->next=NULL;
ptr->value=i;
计数++;
}
返回1;
}
无效显示(){
节点*ptr=头部;
while(ptr!=空){
cout value简短回答:

int i = **sp;

不应该用新的方式分配对象。代码看起来像java。C++中,必须删除新分配的所有东西。在C++中,可以写:

SmartPointer sp;
sp.push(99);
int i = *sp;

sp
不是智能指针-它是指向
SmartPointer
类的普通老式哑指针。
*sp
使用内置的解引用操作符,生成
SmartPointer
类型的左值。它不调用
SmartPointer::operator*()
-为此,您需要编写
**sp
(双星)

现在还不清楚为什么要在堆上分配
SmartPointer
实例。这是一件不寻常的事情(同样,你也会泄露它)。我很确定你最好使用它

SmartPointer sp;
sp.push(99);
等等