2016-04-17 260 views
0

我必须使用称为Robot_parts []为每个part_rect结构(PART_NUM,part_name,part_quantity,part_cost)结构阵列与指针

并通过空隙显示功能,我要显示Robot_parts []数组的结构体数组完全通过指针,但我不知道如何,我不知道如何声明Robot_parts []以及是否必须在括号内放置任何数字值。

到目前为止,我有:

#include <iostream> 
#include <string> 

using namespace std; 
void display(); 

struct part_rec 
{ 
    int part_num; 
    string part_name; 
    int part_quantity; 
    double part_cost; 
}; 

int main() 
{ 
    part_rec Robot_parts[ ] = { 
           {7789, "QTI", 4, 12.95}, 
           {1654, "bolt", 4, 0.34}, 
           {6931, "nut", 4, 0.25} 
                }; 
return 0; 
} 

void display() 
{ 
    cout<<Robot_parts[]<<endl<<endl; 
} 

如果我还做了一些其他错误,请让我知道。谢谢!

+0

'COUT << Robot_parts [] << endl << endl;'这不会像你期望的那样工作,C++不能直接打印数组。 –

+0

你认为这应该如何工作:'cout << Robot_parts [] << endl << endl;'??你不是从main()方法调用'display()'。 –

+0

为什么不使用C++容器,例如'vector',而不是一个c风格的数组? – 4386427

回答

0

正如评论中所述,使用C++容器如std::vectorstd::array会更好。

但由于你的教授需要一个老式的数组,你可以尝试像下面的代码 - 见注释进行说明:

#include <iostream> 
#include <string> 
#include <vector> 

using namespace std; 
struct part_rec 
{ 
    int part_num; 
    string part_name; 
    int part_quantity; 
    double part_cost; 
}; 

// You have to pass a pointer (to the array) and the size of the array 
// to the display function 
void display(part_rec* Robot_parts, int n); 


// Make a function so that you can "cout" your class directly using << 
// Note: Thanks to @BaumMitAugen who provided this comment and link: 
//  It makes use of the so called Operator Overloading - see: 
//  https://stackoverflow.com/questions/4421706/operator-overloading 
//  The link is also below the code section 
std::ostream &operator<<(std::ostream &os, part_rec const &m) 
{ 
    // Note - Only two members printed here - just add the rest your self 
    return os << m.part_num << " " << m.part_name; 
} 


int main() 
{ 
    part_rec Robot_parts[] { 
           {7789, "QTI", 4, 12.95}, 
           {1654, "bolt", 4, 0.34}, 
           {6931, "nut", 4, 0.25} 
          }; 
    display(Robot_parts, 3); 
    return 0; 
} 

void display(part_rec* Robot_parts, int n) 
{ 
    // Loop over all instances of your class in the array 
    for (int i = 0; i < n; ++i) 
    { 
     // Print your class 
     cout << Robot_parts[i] << endl; 
    } 
} 

通过@BaumMitAugen推荐链接: Operator overloading

+1

对于阅读这个答案的初学者来说:它使用了所谓的[运算符重载](https://stackoverflow.com/questions/4421706/operator-overloading)(推荐阅读)。 –

+0

谢谢! :) –