I'm reading 'C++ Programming in easy steps' and the program the book has given me will not compile.

Compile line -> g++ -g -Wall "${ARG}" -o "${ARG:: -4}" && ARG is command line argument 1.

object.cpp:7:5: error: ‘string’ does not name a type
     string color;
     ^
object.cpp:14:19: error: ‘string’ has not been declared
     void setColor(string clr) { color = clr; }
                   ^
object.cpp:18:5: error: ‘string’ does not name a type
     string getColor() { return color; }
     ^
object.cpp: In member function ‘void Dog::setColor(int)’:
object.cpp:14:33: error: ‘color’ was not declared in this scope
     void setColor(string clr) { color = clr; }
                                 ^
object.cpp: In function ‘int main()’:
object.cpp:26:26: error: invalid conversion from ‘const char*’ to ‘int’ [-fpermissive]
     fido.setColor("brown");
                          ^
object.cpp:14:10: error:   initializing argument 1 of ‘void Dog::setColor(int)’ [-fpermissive]
     void setColor(string clr) { color = clr; }
          ^
object.cpp:28:39: error: ‘class Dog’ has no member named ‘getColor’
     std::cout << "Fido is a " << fido.getColor() << " dog" << std::endl;





#include <iostream>
#include <string.h>

class Dog
{
    int age, weight;
    string color;

    public:

    void bark() { std::cout << "WOOF!" << std::endl; }
    void setAge(int yrs) { age = yrs; }
    void setWeight(int lbs) { weight = lbs; }
    void setColor(string clr) { color = clr; }

    int getAge() { return age; }
    int getWeight() { return weight; }
    string getColor() { return color; }
};

int main()
{
    Dog fido;
    fido.setAge(3);
    fido.setWeight(15);
    fido.setColor("brown");

    std::cout << "Fido is a " << fido.getColor() << " dog" << std::endl;
    std::cout << "Fido is " << fido.getAge() << " Years old" << std::endl;
    std::cout << "Fido weight " << fido.getWeight() << " pounds" << std::endl;

    fido.bark();

    return 0;
}

<string.h> (also available as <cstring>) is a C header that declares functions that work on C strings (i.e. 0-terminated char*s). The std::string class is defined in <string>. You'll also need to refer to it as std::string as it's located in that namespace.

Remove #include <string.h> and replace with #include <string>
As the string object is in the std namespace, you can either replace all functions and variables in the Dog class that contain string to std::string
or
put using std::string; before the Dog class.

Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.