2016-11-15 74 views
0

你好,我一直在试图弄清楚这一点。我在这个函数中传递一个对象来比较两个不同的卷,但是我需要使用两个不同的类(继承)才能接收卷的信息。当我尝试传递该对象时,我很难尝试将circleType和cylinderType类与传递的对象一起使用。我不知道如何正确地处理这个问题,但我想弄清楚如何在比较函数中使用两个不同的类。比较两个不同类别的对象?

bool equalVolume(const circleType&, const cylinderType& ct) 
{ 
    if (ct.CalcVolume != Calvolume()) 
    { 
     return false; 
    } 
    else 
    { 
     return true; 
    } 
} 
+1

你做了一些错别字纠正他们,然后它会工作,如果'circelType'和'cylinderType'具有'calcVolume'函数 –

+1

您可能意指'返回(cleft.CalcVolume()== cright.CalcVolume()); '作为函数的主体''bool equalVolume(const circleType&cleft,const cylinderType&cright)' –

+0

您可能会重新设计您的应用程序,以使'class circleType'和'class cylinderType'继承自* common *超类'GeometricalObject',虚拟double CalcVolume(void)const;'方法。然后你只需要一个'bool sameValue(const GeometricalObject&left,GeometricalObject&right);'函数 –

回答

2

您的实施有多个问题。您会收到两种形状,但circleType没有变体名称。然后我看到你试图调用没有变量的函数calcVolume。你怎么能计算什么都没有?那么,你不能。您必须使用圆圈的名称并参考它。

//         v---- Give a name to your circle 
bool equalVolume(const CircleType& myCircle, const CylinderType& myCylinder) { 
//  v---- Call calcVolume with myCircle 
    if (myCircle.calcVolume() != myCylinder.calcVolume()) { 
//  call with the cylinder --^ 
     return false 
    } else { 
     return true; 
    } 
} 

顺便说一句,因为相比已经是bool类型的表达式,可以缩小你的函数是:

bool equalVolume(const CircleType& myCircle, const CylinderType& myCylinder) { 
    return myCircle.calcVolume() == myCylinder.calcVolume(); 
} 

我宁愿创建一个返回音量的功能并将实现留给用户。它看起来像:

using volume_t = double; 

struct Circle { 
    volume_t volume() const { 
     // return volume here 
    } 
}; 

struct Cylinder { 
    volume_t volume() const { 
     // return volume here 
    } 
}; 

然后,而不是使用isVolumeEqual功能,只要做到这一点:

if (myCircle.volume() == myCylinder.volume()) { 
    // code here ... 
} 

如果你真的想要实现的容量相等的功能,我会做它像即:

template<typename S1, typename S2> 
auto volumeEqual(const S1& s1, const S2& s2) -> decltype(s1.volume() == s2.volume()) { 
    return s1.volume() == s2.volume(); 
} 

这样一来,你实施具有volume()函数的所有可能的形状一volumeEqual

2

我还以为这可能是这个样子:

bool equalVolume(const circleType& cir, const cylinderType& cyl) 
{ 
    return cir.CalcVolume == cyl.CalcVolume; 
} 

作为另一个用户已经指出的那样,我可能会添加一个体积()getter函数并用它来代替直接访问CalcVolume (这可能是一个数据成员)。

PS:编写一个像这样比较卷的函数看起来是多余的,因为您总是可以比较if()条件中的卷。

+0

函数是一个好主意,它可以帮助代码的可读性,并且可以用在算法中 –