如何访问print()函数中的类变量



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

编译时,我得到错误:

Book.cpp:14:19:错误:未在此作用域中声明"title"cout<lt"标题:"<lt;标题<lt;endl;

是否存在在不更改print((参数的情况下调用类变量的方法?

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

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

最新更新