2012-03-29 194 views
12

我在学习Adam Drozdek的书“C++中的数据结构和算法”,好吧,我在我的vim中输入了第15页的代码,并将其编译到了我的Ubuntu 11.10的终端中。'cout'没有命名一个类型

#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; 

但是有一些错误:

[email protected]:~$ 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 

我已搜查thisthisthisthis,但我无法找到答案。

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

+5

main()'在哪里? – Makoto 2012-03-29 23:26:25

+1

你错过了你的主。代码在函数之外,被编译器认为是变量声明,类声明,结构声明或其他类似的命令。只需将所有底部代码放入int main() – 2012-03-29 23:29:19

回答

23

的问题是,你的代码有确实的印刷是在任何函数之外。 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; 
} 
5

您缺少围绕程序代码的函数声明。以下应解决您的错误:因为您尝试设置一个整数值(30)为一个字符串属性

#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; 
} 

的错误,那么你(像“从int到char无效的转换*”)为(名)与

node2.name=30; 

我觉得

node2.age=30; 

是正确的。

2

main()函数被错过。在C++中应该有一个main()函数,并且你应该把cout放入一个函数中。

error prog.cpp:4:14: error: cannot convert 'std::basic_ostream<char>' to 'bool' in initialization 
bool b=cout<<"1"; 
1

如果你想使用COUT功能外,你可以通过收集由COUT在boolean.see下面的例子

#include<iostream> 
using namespace std; 

bool b=cout<<"1"; 

int main() 
{ 

return 0; 

} 

输出返回的值做

int main() 
{ //code 
    return 0; 
} 

会帮到你。这个问题通常发生在那些正在学习书籍的人身上,他们在几章之后通常不会使用主要功能。

-1

包括: