【问题标题】:How can I access the class variables inside the print() function here?如何在此处访问 print() 函数中的类变量?
【发布时间】:2021-03-22 07:43:23
【问题描述】:

书.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:错误:“标题”未在此范围内声明 cout

有没有在不改变print()参数的情况下调用类变量?

【问题讨论】:

  • 你应该写void Book::print(){...}。
  • Book.cpp 中的打印函数不是成员函数。我想你想把它改成void Book::print() { /*...*/ }

标签: c++ oop


【解决方案1】:

既然是Book的成员函数,应该是

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

【讨论】:

    猜你喜欢
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    • 2012-11-04
    • 2011-11-03
    • 2023-01-16
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多