我有一个程序,我想在其中阅读有关书籍的信息,按结构组织 - 例如从控制台读取作者,然后将其打印在标准输出上,如下所示。然而,Visual Studio 编译器 (IDE) 给出了一个错误 - this declaration has no storage class or type specifier
,当我尝试将结构的地址分配给指针时:ptstr = &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
。
关于c++ - 指向 C++ 中的结构的指针 - 从控制台读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48966618/