我有一个程序,我想在其中读取有关结构化组织的书籍信息,例如从控制台读取作者,然后将其打印在标准输出上,如下所示。但是,当我尝试向指针分配结构的地址时,Visual Studio编译器(IDE)给出错误-this declaration has no storage class or type specifierptstr = &a;我想问一下我做错了什么方法?

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
struct Book {
    string title;
    string author;
    string price;

};
Book a;
Book *ptstr;
ptstr = &a;
int main()
{


    cin >> ptstr->author;
    cout << ptstr->author;
    return 0;
}

最佳答案

ptstr = &a;


这是无效的,因为不允许您在全局范围内分配变量。要解决此问题,请将声明更改为:

Book *ptstr = &a;


您也可以将任务移到main。最好的建议是不要使用全局变量,而是将两个对象都移至main

Live Example

08-16 08:48