我正在学习 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

我搜索了,,,,,,,,,但我找不到答案。

任何帮助,将不胜感激:)

答案

问题在于您拥有的代码打印不在任何函数之外。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;
}

来自: stackoverflow.com