1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Errors in Program

Discussion in 'C' started by inspiration, Mar 27, 2010.

  1. inspiration

    inspiration New Member

    Joined:
    Feb 15, 2010
    Messages:
    85
    Likes Received:
    0
    Trophy Points:
    0
    Question 1 (basic classes):
    Consider the following code.
    Code:
    #include <iostream>
    using namespace std;
    class Book {
    Book(int numPages);
    void SetPages(int numPages);
    int GetPages() const;
    private:
    int pages;
    }
    Book::Book(int numPages) {
    pages = numPages;
    }
    Book::SetPages(int numPages) {
    pages = numPages;
    }
    int Book::GetPages() {
    return pages;
    }
    int main() {
    Book textbook;
    textbook.SetPages(970);
    int numPages = textbook.GetPages();
    cout << "The textbook has " << numPages << " pages." << endl;
    int ripout = 5;
    textbook.SetPages(numPages - ripout);
    cout << "I just tore out " << ripout << " pages." << endl;
    cout << "It now has " << textbook.GetPages << " pages left." << endl;
    return 0;
    }
    What errors are in this code? (There are at least 5.)
     
  2. meyup

    meyup New Member

    Joined:
    Feb 15, 2010
    Messages:
    102
    Likes Received:
    0
    Trophy Points:
    0
    Hey inspiration! Try this,
    Code:
    #include <iostream>
    template<class B1, class B2>
    class MyBook {
     B1 book1;
     B2 book2;
    public:
     MyBook(B1 b1, B2 b2) : book1(b1), book2(b2)
         {  }
     template<class B3, class B4>
     friend std::ostream& operator<<(std::ostream& os,
                                     const MyBook<B3, B4>&);
    };
    template<class B1, class B2>
    std::ostream& operator<<(std::ostream& os,
                             const MyBook<B1, B2>& bb)
    {
     std::cout<<"My book has " << bb.book1 << ' ' << "pages" << std::endl;
     std::cout<<"I just tore out " << bb.book1 - bb.book2 << ' ' << "pages" << std::endl;
     std::cout<<"My book now has " << bb.book2 << ' ' << "pages" << std::endl;
     return os;
    }
    int main()
    {
     int a = 970;
     int b = 965;
     MyBook<int,double> my_twothings(a, b);
     std::cout << my_twothings << std::endl;
     return 0;
    }
    
     
  3. inspiration

    inspiration New Member

    Joined:
    Feb 15, 2010
    Messages:
    85
    Likes Received:
    0
    Trophy Points:
    0
    Thanks, You are great!
    :D
     
  4. meyup

    meyup New Member

    Joined:
    Feb 15, 2010
    Messages:
    102
    Likes Received:
    0
    Trophy Points:
    0
    My Pleasure...
    :)
     

Share This Page