为什么我得到"表达式不可分配"错误?

时间:2014-12-06 04:00:17

标签: c++ xcode unit-testing

我上了一个私人名字,出售单位和剩余单位的课程。

我制作了两个返回的类方法,销售的单位和剩余的单位作为整数。

我想将销售的单位从最大到最小排序,但我在评论中解释时会出现错误。

我做错了什么,这是非常明显的事情吗?

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

const int MAX_SIZE = 1000;
const char FILE_NAME[14] = "inventory.txt";

//make an Item class
class Item
{
private:
    string name;
    int sold, remain;
public:
    void set_name(string _name);
    void set_sold(int _sold);
    int get_sold(int);
    void set_remain(int _remain);
    int get_remain(int);
    void print();
};

//I erased all the methods setting name, sold, and remaining, they work though

int Item::get_sold(int s)
{
    s = sold;

    return s;
}
int Item::get_remain(int r)
{
    r = remain;

    return r;
}

//greatest to least units sold
void sort_sold(Item gL[], int ct) // ct is a global constant set to 1000
{
    //local variables
    int smallestPos;
    int temp;

    //for every position in the array
    for(int i=0;i<ct;i++)
    {
        //find the smallest element starting at that point
        smallestPos = i;
        for(int j=i+1;j<ct;j++)
        {
            if(gL[j].get_sold(j) < gL[smallestPos].get_sold(smallestPos))
            {
                //found a smaller one, remember and keep going
                smallestPos = j;
            }
        }
        //see if we found something smaller than gL[i].get_sold(i)
        if(gL[i].get_sold(i) > gL[smallestPos].get_sold(smallestPos))
        {
            //we did find a smaller one, so swap with gL[i].get_sold(i)
            temp = gL[i].get_sold(i);
            gL[i].get_sold(i) = gL[smallestPos].get_sold(smallestPos); //not assignable?
            gL[smallestPos].get_sold(smallestPos) = temp;              //not assignable?
        }
    }

}

1 个答案:

答案 0 :(得分:1)

在C ++中int是一种原始类型,而不是类,就像在Java中一样。如果您返回int,则只需将其作为常量返回,所以

gL[i].get_sold(i) = something;

是不可能的。你需要为你的班级准备好适当的吸气剂和设定器:

int Item::get_sold() {
    return sold;
}
void Item::set_sold(int s) {
    sold= s;
}

//..

if(gL[i].get_sold() > gL[smallestPos].get_sold()) {

    temp = gL[i].get_sold();
    gL[i].set_sold(gL[smallestPos].get_sold()); 
    gL[smallestPos].set_sold(temp);      
}

另外,请考虑使用std::vector模板和排序功能:

http://www.cplusplus.com/reference/algorithm/sort/

#include <algorithm>
#include <vector>

// Create comparsion function (or simple overload an < operator):
bool compareSold(Item i1, Item i2) {
    return i1.get_sold() < i2.get_sold();
}    

// replace static array with std::vector<Item>
std::vector<Item> arrItems();

// You can init it with your static array, but better way would be
// to delete a static array and use this vector all the time.
arrItems.assign(gL, gL+ct); 

// Sort it
std::sort (arrItems.begin(), arrItens.end(), compareSold);

// If you need to convert std::vector to [] array, you can use &arrItems.front()
Item* i = &arrItems[0];