c++ - ‘cout’ 没有命名类型

标签 c++

我正在学习 Adam Drozdek 的书“C++ 中的数据结构和算法”,嗯,我在 vim 中输入了第 15 页的代码,并在我的 Ubuntu 11.10 的终端中编译了它。

#include <iostream>
#include <cstring>
using namespace std;

struct Node{
    char *name;
    int age;
    Node(char *n = "", int a = 0){
        name = new char[strlen(n) + 1];
        strcpy(name, n);
        age = a;
    }
};

Node node1("Roger", 20), node2(node1);
cout << node1.name << ' ' << node1.age << ' ' << node2.name << ' ' << node2.age;
strcpy(node2.name, "Wendy");
node2.name = 30;
cout << node1.name << ' ' << node1.age << ' ' << node2.name << ' ' << node2.age;

但是有一些错误:

oo@oo:~$ g++ unproper.cpp -o unproper
unproper.cpp:15:23: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
unproper.cpp:16:1: error: ‘cout’ does not name a type
unproper.cpp:17:7: error: expected constructor, destructor, or type conversion before ‘(’ token
unproper.cpp:18:1: error: ‘node2’ does not name a type
unproper.cpp:19:1: error: ‘cout’ does not name a type

我搜索过 this , this , thisthis ,但我找不到答案。

任何帮助将不胜感激:)

最佳答案

问题在于您拥有的用于打印的代码不在任何功能范围内。不是 C++ 中的声明的语句需要在函数内部。例如:

#include <iostream>
#include <cstring>
using namespace std;
    
struct Node{
    char *name;
    int age;
    Node(char *n = "", int a = 0){
        name = new char[strlen(n) + 1];
        strcpy(name, n);
        age = a;
    }
};


int main() {
    Node node1("Roger", 20), node2(node1);
    cout << node1.name << ' ' << node1.age << ' ' << node2.name << ' ' << node2.age;
    strcpy(node2.name, "Wendy");
    node2.name = 30;
    cout << node1.name << ' ' << node1.age << ' ' << node2.name << ' ' << node2.age;
}

关于c++ - ‘cout’ 没有命名类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9935027/

相关文章:

c++ - 如何强制 C++ 编译器使用寄存器?

c++ - 如何在MFC中创建 "CArray<CArray<CString>>& results"?

c++ - 我可以合法地写入常量 vector 指向的数据吗?把它分类?

c++ - OpenCV 中具有公差的模板匹配

c++ - 如何使用堆栈C++以相反的顺序读取文件和打印

使用 antlr 和 line 指令的 C++ 代码插入

c++ - 在 Windows 中分配内存

c++ - 如何知道 std::cin 是否来自重定向?

c++ - 在 VS2010 中禁用迭代器调试

c++ - 用于片段着色器的 OpenGL GLSL 绑定(bind)采样器