‘cout’ does not name a type

后端 未结 5 2154
死守一世寂寞
死守一世寂寞 2020-12-01 11:02

I was learning Adam Drozdek\'s book \"Data Structures and Algorithms in C++\", well, I typed the code in page 15 in my vim and compiled it in terminal of my Ubuntu 11.10.

5条回答
  •  独厮守ぢ
    2020-12-01 11:28

    You are missing the function declaration around your program code. The following should solve your error:

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

    The error you then get (something like "invalid conversion from int to char*") is because you try to set an integer value (30) to a string attribute (name) with

    node2.name=30;
    

    I think

    node2.age=30;
    

    would be correct.

提交回复
热议问题