首页 > 解决方案 > 如何在这里访问 print() 函数中的类变量?

问题描述

书.h

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

};

书本.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;
}

编译时,我收到错误:

Book.cpp:14:19: 错误: 'title' 未在此范围内声明 cout<<"Title: "<<title<<endl;

无论如何调用类变量而不更改 print() 的参数?

标签: c++oop

解决方案


由于它是 Book 的成员函数,它应该是

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

推荐阅读