c++ - 指向 C++ 中的结构的指针 - 从控制台读取?

标签 c++ pointers struct cin cout

我有一个程序,我想在其中阅读有关书籍的信息,按结构组织 - 例如从控制台读取作者,然后将其打印在标准输出上,如下所示。然而,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

Live Example

关于c++ - 指向 C++ 中的结构的指针 - 从控制台读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48966618/

相关文章:

c++ - Cast模板(矩阵)类

c - 结构体数组不保存

c# - 使用 C# 中的结构调用 C++ 代码

c - 使用 int 和 size_t 时的结果差异

c++ - 结构构造函数语法

c++ - DirectInput 未解析的外部符号

c++ - 检测到堆损坏

c++ - 从 utsname 中找出 Linux 操作系统名称

c# - 为什么我们不能使用指向字符串的指针?

c - 如何在没有 valgrind 提示的情况下使结构指向自身