c++ - 不兼容的类型 - 是因为数组已经是指针了吗?

标签 c++

在下面的代码中,我创建了一个基于 books 结构的对象,并让它保存多个“books”,我设置的是一个数组(即定义/启动的对象)。然而,每当我去测试我的指针知识(实践有帮助)并试图创建一个指向创建的对象的指针时,它都会给我错误:

C:\Users\Justin\Desktop\Project\wassuip\main.cpp|18|错误:将“books”分配给“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;
    }
}

最佳答案

An array is not a pointer

参见 How do I use arrays in C++?了解详情。

关于c++ - 不兼容的类型 - 是因为数组已经是指针了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13041497/

相关文章:

c++ - 如何为 3 个数据集创建多 MAP

c++ - 向 QDockWidgets 区域添加滚动条

c++ - C/C++ 服务器不发送最后几行文件

c++ - Windows Mobile 无法卸载

c++ - 如何声明任意深度的对?

c++ - VTK:直到用户交互后 View 才会更新

c++ - 将 ZeroMQ 与 Boost::ASIO 一起使用

C++:打破主循环

c++ - 当属性位置 != 0 时,着色器不输出任何内容

c++ - 强制 node-gyp 使用 C++11