我遇到的问题是字符串参数。我不确定如何使用它。我只希望分类从一开始就具有未定义长度的字符串,直到用户输入为止。当我输入字符串分类时,我得到的错误是'std::string classification' 的声明隐藏了一个参数。将字符串参数传递给类成员的正确方法是什么?
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Shapes
{ //Begin Class Definition
private:
float side;
float height;
int exponent;
string *classification;
public:
Shapes(float side, float height, string * classification);
//CONSTRUCTOR
~Shapes(){};
//DESTRUCTOR
float area(float side, float height, string *classification);
float perimeter(float side, float height, string *classification);
}; // End Class Definition
int power(float side, int exponent)
{
int i;
int total[exponent];
float sum;
for ( i = 0 ; i < exponent ; i ++ )
{
total[i]= side;
sum *= total[i] ;
}
return sum;
}
float Shapes::area(float side, float height, string *classification)
{
float area=0.0;
string classification;
getline(cin,string);
if (classification == "square" )
{
area = power(side,2);
return area;
}
if (classification == "triangle" )
{
area = (side* height) / 2 ;
return area;
}
if (classification == "hexagon" )
{
float constant = 2.598706;
area= constant * power(side,2);
return area;
}
if (classification == "circle" )
{
}
};
最佳答案
您正在重新声明名为classification 的string
。您只需在类声明 中声明该变量一次,它就可以在您的所有成员函数中使用。您还为您的参数 使用了相同的名称,这令人困惑且危险。
你也应该小心你在这里用指针做什么,似乎你不确定什么时候使用它们,或者使用引用。如果您确实尝试像这样比较您的 string* classification
参数,if (classification == "triangle")
,您会意识到您无法比较 std::string* 到 const char*
理想情况下,您应该在这里使用枚举,就像这样。
class Shape
{
public:
enum Classification { SQUARE, TRIANGLE, CIRCLE };
}
Shape::Area(float side, float height, Classification shapeClass)
{
if(shapeClass == SQUARE) {} // Etc
}
甚至更好你会使用继承和多态和重载函数,如area ()
class Shape { virtual float Area(); };
class Triangle : public Shape { virtual float Area(); };
关于c++ - 从类定义中传递字符串指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11821570/