0

我正在编写一个控制台应用程序,它接收产品的净价格并打印出总价格,在处理 main 时,我可以遇到一个问题,我expression must have integral or unscoped enum type在线路cout << "Software costs " + product[0]->getGrossPrice();cout << "Book costs " + product[1]->getGrossPrice();

这是我到目前为止写的内容:

#include "Software.h"
#include "Book.h"
#include "Product.h"
#include <vector>
#include <iostream>

using namespace std;

int main() {

    double price;

    vector<Product*> product(8);

    Software *software;
    Book *book;

    cout << "Enter price of software";
    cin >> price;

    product[0] = new Software(price);

    cout << "Software costs " + product[0]->getGrossPrice();

    cout << "Enter price of book";
    cin >> price;

    product[1] = new Book(price);

    cout << "Book costs " + product[1]->getGrossPrice();

任何帮助将不胜感激~

4

2 回答 2

0

问题是运算符优先级,这一行

cout << "Software costs " + product[0]->getGrossPrice();

其实是这样的:

cout << ("Software costs " + product[0]->getGrossPrice());

因此,您正在尝试添加字符串文字和无法添加到字符串文字的内容。

于 2020-02-04T15:03:18.803 回答
0

ostream& operator <<是最好的选择,因为它被重载以接受任何原始类型并将它们转换为字符串流。将 + 用于不同类型通常效果不佳。

代替

cout << "Software costs " + product[0]->getGrossPrice();

cout << "Software costs " << product[0]->getGrossPrice();

那应该这样做。

于 2020-02-04T15:13:16.737 回答