注册 登录
编程论坛 C++教室

这段程序为什么不输出啊?

thlgood 发布于 2011-11-04 20:45, 758 次点击
Windows 7下居然提示

程序代码:

#include <iostream>
#include <cstring>
using namespace std;

class Books
{
    private:
        float Price;
        string Author;
    public:
        Books(float price, string author);
        void ShowInfo();
        Books& operator =(const Books &bookname);
};

Books& Books::operator = (const Books &bookname)
{
    if (&bookname == this)
        return *this;
    else
    {
        Books temp(bookname.Price, bookname.Author);
        return temp;
    }
}

Books::Books(float price, string author)
{
    Price = price;
    Author = author;
}

void Books::ShowInfo()
{
    cout << "Book Price" << '\t' << Price << endl;
    cout << "Book Author" << '\t' << Author << endl;
}

int main()
{
    Books APEU(67, "Bob");
    APEU.ShowInfo();
    return 0;
}

9 回复
#2
yuccn2011-11-04 20:51
void Books::ShowInfo()
{
    cout << "Book Price" << '\t' << Price << endl;
    cout << "Book Author" << '\t' << Author.c_str() << endl;
}

注意红色的地方
#3
Cplus菜鸟2011-11-04 21:05
你把#include <cstring>改成#include <string>就没有问题了
#4
thlgood2011-11-04 21:06
回复 2楼 yuccn
谢谢。可是还是不能通过
#5
Cplus菜鸟2011-11-04 21:07
Books& Books::operator = (const Books &bookname)
{
    if (&bookname == this)
        return *this;
    else
    {
        Books temp(bookname.Price, bookname.Author);
        return temp;
    }
}你这段代码,有问题,容易造成运行错误,你返回的一个临时对象的引用!函数返回的时候,对象都释放了,你还返回一个对象的引用
#6
thlgood2011-11-04 21:28
我该了一下,可还是不对

程序代码:

#include <iostream>
#include <string>
using namespace std;

class Books
{
    private:
        float Price;
        string Author;
    public:
        Books(float price, string author);
        void ShowInfo();
        Books operator =(const Books &bookname);
};

Books Books::operator = (const Books &bookname)
{
    if (&bookname == this)
        return *this;
    else
        return Books(bookname.Price, bookname.Author); //这里
}

Books::Books(float price, string author)
{
    Price = price;
    Author = author;
}

void Books::ShowInfo()
{
    cout << "Book Price" << '\t' << Price << endl;
    cout << "Book Author" << '\t' << Author << endl;
}

int main()
{
    Books APEU(67, "Bob");
    APEU.ShowInfo();
    return 0;
}

#7
麓橥2011-11-05 21:16
2楼的没问题,试过了
#8
何凡2011-11-06 13:49


六楼的代码我有DEV-C++试了下,管用。只是在return 0;前加了个system("pause");
输出的是:
Book price   67
Book Author  Bob

#9
deng09812011-11-06 15:28
试了。 把cstring改为string输出正常。有可能是你编译环境的问题!
#10
lwei2011-11-06 23:01
程序应该没有问题,和你的IDE有关吧?
提一个建议,建议构造函数这样写,
  Books(float price, string author):Price(price), Author(author){};
1