C++ 如何从派生模板类C++;
这里我有来自类C++ 如何从派生模板类C++;,c++,arrays,sorting,templates,C++,Arrays,Sorting,Templates,这里我有来自类ColVol的对象数组,它用int类型的颜色和体积(int)定义三维点。如果颜色介于[1,10]之间,则任务是按体积对数组进行排序。错误在于表达式必须是可修改的左值?,这里仅是函数的声明。我不知道什么类型的排序在这里是最好的,为什么当temp变量是int,object.get_method()(在这种情况下数组是f[]和f[I]。get_volume()是int`)时会给我这个错误?它们是同一类型的 template<class T> class Point3 {
ColVol
的对象数组,它用int
类型的颜色和体积(int
)定义三维点。如果颜色介于[1,10]之间,则任务是按体积对数组进行排序。错误在于表达式必须是可修改的左值
?
,这里仅是函数的声明。我不知道什么类型的排序在这里是最好的,为什么当
temp
变量是int,object.get_method()(
在这种情况下数组是f[]和f[I]。get_volume()
是
int`)时会给我这个错误?它们是同一类型的
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;
}
}
}
}
模板类点3{
tx,y,z;
公众:
第3点();
无效打印()常量;
};
模板类ColPoint3:公共点3{
U色;
公众:
ColPoint3();
无效打印()常量;
};
模板类ColVol:public ColPoint3{
V体积;
公众:
ColVol();
无效打印()常量;
V get_volume(){
返回量;
}
};
int main(){
常数int n=2;
ColVol*f;
f=新ColVol[n];
对于(int i=0;i=1 | | f[k].get_color()f[j+1].get_volume()){
temp=f[j]。获取卷();
f[j]。获取卷()=f[j+1]。获取卷();
f[j+1]。获取卷()=temp;
}
}
}
}
您需要以下修复(至少要编译此文件):
将方法get_color添加到ColPoint3:
U get_color(){
return color;
}
更改get_卷的签名:
V& get_volume() {
^~~~!
return volume;
}
最后定义构造函数
[编辑]
至于排序,为什么不使用std::sort
std::sort(f, f + n, [](auto &lop, auto &rop){
return lop.get_volume() < rop.get_volume();
});
排序(f,f+n,[](自动和lop,自动和rop){
返回lop.get_volume()