2012-09-06 25 views
1

我正在写一个小人计算机模拟,我想重载索引运算符[]。我创建了一个名为LMC的类,并完成了以下操作:运算符C++中的重载和数组处理

#include <iostream> 

using namespace std; 

class LMC 
{ 
    public: 
     LMC(); 
     void display(); 
     int& operator[](int index); 
     ~LMC(); 
    private: 
     int **array; 
}; 

LMC::LMC() 
{ 
    array = new int*[100]; 
    for(int i = 0; i < 100; i++) 
    { 
     array[i] = new int[3]; 
    } 
    return array; 
} 

void LMC::display() 
{ 
    for(int i = 0; i < 100;i++) 
    { 
     for(int j = 0; j <3;j++) 
     { 
      array[i][j] = 0; 
      array[i][2] = i; 
      cout << array[i][j]<<" "; 
     } 
     cout << endl; 
    } 
} 
int& LMC::operator[](int index) 
{ 
    return array[index][2]; 
} 

    LMC::~LMC() 
    { 
    for(int i =0; i < 100 ; i++) 
    { 
     delete [] array[i]; 
    } 
    delete [] array; 
    array = NULL; 
    } 

    int main() 
    { 
    LMC littleman; 
    while(true) 
    { 
     int mailbox; 
     int function; 
     cout << "What is Mailbox number?" << endl; 
     cin >> Mailbox; 
     cout << "What is the function you want to use?" <<endl; 
     cin >> finction; 
     //the function is numbers eg 444 and 698; 
     littleman.display(); 
     littleman[Mailbox] = function; 
     } 
    return 0; 
} 

我可以在没有错误的情况下运行该程序。当我说mailbox = 0function = 123是没有问题的。

这显示:

0 0 0 
1 0 0 
2 0 0 
3 0 0 
//continuing to 99 

该显示是错误的。以下必须显示:

0 0 123 
1 0 0 
2 0 0 
//continuing to 99 

我有一个逻辑上的错误还是我重写阵列显示原始和如何解决呢?

+7

请为自己节省麻烦,并为您的内部数组使用'std :: vector >'而不是'int **'。 –

+0

'0 0 0'这是'LMC :: display()'的输出吗? – Andrey

+0

@Andrey是的,这是输出。 –

回答

0

这些线

array[i][j] = 0; 
    array[i][2] = i; 

LMC::display()破坏阵列的你想显示的内容。

此外,在void LMC::display();末尾还有一个额外的分号,所以您的代码不应该编译。

0

您的代码有许多,不会让它编译即错误:在LMC()构造

  • ,你有return array;。构造函数从不返回任何东西(它们甚至没有返回类型),所以你不能在其中使用return
  • void LMC::display()之后,你有一个;,这是一个错误,因为这不是一个定义,而是实现。你应该省略它,只是离开void LMC::display() { <...> }
  • void LMC::display()最后缺失关闭},就在operator[]之前。
  • main()你有Mailbox错字(资本M在一种情况下,与正常米在另一个,在C+++ Mailboxmailbox不同变量)和finction而不是函数。

至于你的问题,你重写阿雷的值display()功能:

array[i][j] = 0; 
array[i][2] = i; 

这就是为什么你没有看到任何结果。