【问题标题】:'&' illegal operation on bound member function expression error'&' 对绑定成员函数表达式错误的非法操作
【发布时间】:2016-07-10 04:17:11
【问题描述】:

好的,这是我的代码:

#include "driver.h"
#include "stdafx.h"
#include "Book.h"
#include "Author.h"
#include <vector>

void displayBooks(const vector<Book>& books)
{
    // students need to write the code for this function
    for (int i = 0; i < &books.size; i++)
    {
        std::cout << &books[i] << std::endl;
    }
}

int main()
{

    // create a vector for storing the account objects
    vector<Book> myBooks;

    // create three Author objects
    Author p1("J.K.Rowling", "Edinburgh, Scotland");
    Author p2("Suzanne Collins", "Connecticut, USA");
    Author p3("J.R.R. Tolkien", "Bournmouth, England");

    // Create three Book objects
    Book b1(p1, "Harry Potter and the Sorcerer's Stone", 256, 24.95);
    Book b2(p2, "Mockingjay", 400, 12.99);
    Book b3(p3, "The Hobbit", 322, 14.29);

    // add the books to the vector
    myBooks.push_back(b1);
    myBooks.push_back(b2);
    myBooks.push_back(b3);

    // call the displayBooks function to display the books
    displayBooks(myBooks);
    cout << "\n\n";

    system("PAUSE");
    return 0;
}

最上面的部分是给我带来麻烦的 displayBooks 功能。我不断得到一个 '&' 对绑定成员函数表达式的非法操作 错误。我该如何解决这个问题?

【问题讨论】:

  • i &lt; books.size() 可能还有std::cout &lt;&lt; books[i],假设Book 提供了一个合适的operator&lt;&lt; 过载。

标签: c++


【解决方案1】:

&amp;books.size 不是有效的表达式。

size 是std::vector 的成员函数。调用成员函数需要使用books.size()。

&amp; 在该表达式中的存在导致编译器认为您可能正在尝试获取指向该类的成员函数的指针,该指针可以使用 &amp;std::vector&lt;Book&gt;::size 获得。但是,您不能使用类的对象获得指向该类的成员函数的指针。也就是将消息'&'非法操作绑定成员函数错误翻译成简单的英文。

【讨论】:

  • 好的,我将函数更改为 void displayBooks(const vector& books) { for (unsigned int i = 0; i
  • std::cout &lt;&lt; books[i] 仅在您定义函数 std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, Book const&amp; book); 时才有效。
  • 我应该把那个放在哪里?
  • @riahtron3000,在定义 Book 的同一个 .h 文件中声明函数。将实现放在同一个 .cpp 文件中,您可以在其中实现Book 的其余成员函数。如果函数可以内联,也可以在.h文件中实现。
猜你喜欢
  • 2015-03-18
  • 1970-01-01
  • 1970-01-01
  • 2021-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-19
相关资源
最近更新 更多