【问题标题】:Overloading "*" Operator for custom SmartPointer为自定义 SmartPointer 重载“*”运算符
【发布时间】:2013-11-19 20:33:57
【问题描述】:

我试图通过重载 * 运算符直接从指针类访问整数,但似乎 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>test7.cpp(71): 错误 C2440: 'initializing' : 无法从 'SmartPointer' 转换为 'int' 1> 没有可以执行此转换的用户定义转换运算符,或者无法调用该运算符

【问题讨论】:

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


    【解决方案1】:

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

    完全不清楚为什么要在堆上分配SmartPointer 实例。这是一件不寻常的事情(你也泄露了它)。我很确定你会更好

    SmartPointer sp;
    sp.push(99);
    

    等等。

    【讨论】:

      【解决方案2】:

      简短回答:

      int i = **sp;
      

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

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

      【讨论】:

        猜你喜欢
        • 2013-08-15
        • 1970-01-01
        • 1970-01-01
        • 2017-02-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-05
        相关资源
        最近更新 更多