问题描述:

Here I have array of objects from the class ColVol, which defines three - dimensional point with int - type color and volume(int too). The task is to sort the array by volume if the color is between [1,10]. The error is that the expression must be modifiable lvalue?Here are only the declarations of the functions. I don't know what type of sorting will be best here and why gives me that error whentempvariable is int, object.get_method() (in this case the array isf[] and f[i].get_volume()isint`)? They are the same type.

template<class T> class Point3 {

T x, y, z;

public:

Point3();

void print() const;

};

template<class T, class U> class ColPoint3 :public Point3<T> {

U color;

public:

ColPoint3();

void print() const;

};

template<class T, class U, class V> class ColVol :public ColPoint3<T, U> {

V volume;

public:

ColVol();

void print() const;

V get_volume() {

return volume;

}

};

int main() {

const int n = 2;

ColVol<double, int, int> *f;

f = new ColVol<double, int, int>[n];

for (int i = 0; i < n; i++) {

f[i];

}

int temp;

for (int k = 0; k < n; k++) {

if (f[k].get_color() >= 1 || f[k].get_color() <= 10) {

for (int i = 0; i < n - 1; i++)

for (int j = 0; j < n - i + 1; j++)

if (f[j].get_volume() > f[j + 1].get_volume()) {

temp = f[j].get_volume();

f[j].get_volume() = f[j+1].get_volume();

f[j + 1].get_volume() = temp;

}

}

}

}

网友答案:

You need following fixes (at least to make this compile):

add method get_color to ColPoint3:

U get_color(){
    return color;
}

change signature of get_volume:

V& get_volume() {
 ^~~~!
    return volume;
}

and finally define your constructors

[edit]

as for sorting, why not std::sort ?

std::sort(f, f + n, [](auto &lop, auto  &rop){
    return lop.get_volume() < rop.get_volume();
    });
相关阅读:
Top