2012-10-24 15 views
0

在下面的代碼中,我創建了一個基於書籍結構的對象,並讓它擁有多個我設置的「書籍」是一個數組(即定義/啓動的對象)。然而,每當我去測試我的指針知識(練習幫助)並試圖製作一個指向創建對象的指針,它會給我錯誤:不兼容的類型 - 是否因爲數組已經是一個指針?

C:\ Users \ Justin \ Desktop \ Project \ wassuip \ main.cpp | 18 |錯誤:在'書籍'賦值爲'books * [4]'*

的不兼容類型可以請問,這是因爲對象book_arr []已經被認爲是指針,因爲它是一個數組?謝謝(新的C + +只是想驗證)。

#include <iostream> 
#include <vector> 
#include <sstream> 

#define NUM 4 

using namespace std; 

struct books { 
    float price; 
    string name; 
    int rating; 
} book_arr[NUM]; 

int main() 
{ 
    books *ptr[NUM]; 
    ptr = &book_arr[NUM]; 

    string str; 

    for(int i = 0; i < NUM; i++){ 
     cout << "Enter book name: " << endl; 
     cin >> ptr[i]->name; 
     cout << "Enter book price: " << endl; 
     cin >> str; 
     stringstream(str) << ptr[i]->price; 
     cout << "Enter book rating: " << endl; 
     cin >> str; 
     stringstream(str) << ptr[i]->rating; 
    } 

    return 0; 
} 

* 新規範應答後(無錯誤)*

#include <iostream> 
#include <vector> 
#include <sstream> 

#define NUM 4 

using namespace std; 

/* structures */ 
struct books { 
    float price; 
    string name; 
    int rating; 
} book[NUM]; 

/* prototypes */ 
void printbooks(books book[NUM]); 

int main() 
{ 
    string str; 

    books *ptr = book; 

    for(int i = 0; i < NUM; i++){ 
     cout << "Enter book name: " << endl; 
     cin >> ptr[i].name; 
     cout << "Enter book price: " << endl; 
     cin >> str; 
     stringstream(str) << ptr[i].price; 
     cout << "Enter book rating: " << endl; 
     cin >> str; 
     stringstream(str) << ptr[i].rating; 
    } 

    return 0; 
} 

void printbooks(books book[NUM]){ 
    for(int i = 0; i < NUM; i++){ 
     cout << "Title: \t" << book[i].name << endl; 
     cout << "Price: \t$" << book[i].price << endl; 
     cout << "Racing: \t" << book[i].rating << endl; 
    } 
} 
+1

我看你包括''。爲什麼不使用'std :: vector'而不是那些劣質的C數組? – 2012-10-24 10:53:18

+0

@WTP' - 這是否意味着任何實質性的優勢?... – X33

+0

是的,比如體面的語義和清晰的語法,而你實際上是在編寫C++而不是C。參見[DeadMG的這篇文章](http:// codepuppy.co.uk/cpptuts/CClass/CArrays.aspx)爲什麼C陣列可怕。 – 2012-10-24 21:50:26

回答

-5

這是正確的。對於任何數組:

BlahClass myArray[COUNT]; 

&myArray[0]僅相當於myArray。即標識符myArray是指向數組的第一個元素的指針。這就是爲什麼你會聽到它的說法,而不是混淆,「數組和指針在C++中是一樣的」。真正意義的是數組標識符隱式轉換爲指向數組的第一個元素的指針。

+2

儘管你會在這裏說它是真的,它說*「數組和指針在C++中是一樣的」*,那些說它是完全錯誤的人。 –

+0

感謝您的回覆! – X33

+0

@ BenjaminLindley同意。更新我的答案,使其更清晰。 –