简体   繁体   中英

How can I access the class variables inside the print() function here?

Book.h

class Book{
private:
    std::string title;
    std::string author;
    int callNo;
public:
    Book(std::string title,std::string author,int callNo);
    void print();

};

Book.cpp

Book::Book(string title,string author,int callNo){
    this->title=title;
    this->author=author;
    this->callNo=callNo;
}

void print(){
    cout<<"Title: "<<title<<endl;
    cout<<"Author: "<<author<<endl;
    cout<<"Call Number: "<<callNo<<endl;
}

When compiling, I get the error:

Book.cpp:14:19: error: 'title' was not declared in this scope cout<<"Title: "<<title<<endl;

Is there anyway of calling the class variables without changing the parameters of print()?

Since it's a member function of Book, it should be

void Book::print(){
     std::cout << "Title: " << title << std::endl;
     std::cout << "Author: " << author << std::endl;
     std::cout << "Call Number: " << callNo << std::endl;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM