【问题标题】:Error with printout of functions C++打印输出函数 C++ 时出错
【发布时间】:2018-10-09 11:48:44
【问题描述】:

我目前正在为学校做一个程序,这是我第一次在其中使用继承。我的问题是我在尝试打印时从 Visual Studio 收到这些错误。 C2296:

我的打印线是:

    string printOutput = "Book #" << &getCallNumber() << ", title: " << &getTitle() << " by " << &getAuthor() << " pages: " << getNumPages() << ", status: " << getStatus() << ", fees: " /*<< getFees()*/;

函数定义如下:

    const string &getCallNumber() const {
    return callNumber;
}

    const string &getTitle() const {
    return title;
}

    const string &Book::getAuthor() const 
{
    return author;
}

    int Book::getNumPages() const 
{
    return numPages;
}

    Status getStatus() const {
    return status;
}

我还没有定义 getFees 因此为什么它被注释掉了。 当我从他们那里拿走 & 时,我得到更多的错误 任何帮助将不胜感激,我已经坐在这里几个小时了,但就是无法理解它。

【问题讨论】:

  • 你应该使用+来连接字符串而不是&lt;&lt;
  • 你将intStatus连接到string——默认情况下它不会工作
  • &amp;getCallNumber() 不正确。 getCallNumber() 返回一个字符串,加上 & 使它成为一个指向字符串的指针。在打印行中的函数调用之前去掉 &s。您可能还想使用字符串流来创建这样的输出字符串。
  • 我试过了,我得到错误不能添加两个指针。当我从中删除 & 时,我得到 21 个不同的错误,这些错误以 Error C2782 'std::basic_string<_elem> std::operator +(std::basic_string<_elem> &&,const _Elem)': 模板参数 '_Elem' 不明确 a2p1
  • 您不应该在前面添加 &,这将获取字符串的地址,而不是字符串本身。为什么不只是cout 它。你有没有为Status 类重载operator &lt;&lt;

标签: c++ function inheritance


【解决方案1】:

我的打印线是:

string printOutput = "Book #" << &getCallNumber() << ", title: " << &getTitle() << " by " << &getAuthor() << " pages: " <<
> getNumPages() << ", status: " << getStatus() << ", fees: " /*<<
> getFees()*/;

在C++中,如果你想打印一些东西,你可以简单地std::cout它(假设你要打印的东西已经重载operator&lt;&lt;ostream)——不需要构造一个string对象首先

std::cout << "Book #" << getCallNumber() << ", title: " << getTitle() << " by " 
<< getAuthor() << " pages: " << getNumPages() << ", status: " << getStatus() << ", fees: ";

由于getStatus() 返回一个Status,您应该确保Status 类已经为ostream 重载了operator &lt;&lt;。 注意,前面没有&amp; 符号——添加&amp; 将使用string 的地址,而不是string 本身。

更新

您可以在任何地方重载operator&lt;&lt;。如果它不打算访问类的 private 部分,则它不需要是 friend 函数。鉴于Statusenum class,我相信在main 之上重载它就足够了。并给出

enum class Status { AVAILABLE, ON_LOAN, PROCESSED, MISSING, OVERDUE, };

你可以这样做

ostream& operator<<(ostream& os, Status s) {
    switch(s)
    {
        case Status::AVAILABLE:
            os << "AVAILABLE";
            break;
        case Status::ON_LOAN: 
            os << "ON_LOAN";
            break;
        ....//And do the same thing for the other cases

    }
    return os;
}

【讨论】:

  • 我在重载
猜你喜欢
  • 1970-01-01
  • 2020-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多