注册 登录
编程论坛 C++教室

难题啊对于这个"类"

liuguanglei 发布于 2012-11-07 00:36, 413 次点击
//大家帮我看一下怎样用string来给这个矩形输出颜色(例如:输出red)
#include<iostream.h>
#include<string>
class Rectangle
{
public:
    double GetWidth();
    double GetLength();
    double GetArea();
    double GetPerimeter();
    void SetWidth(double myWidth);
    void SetLength(double myLength);
private:
    double length;
    double width;
};
double Rectangle::GetWidth()
{
    return width;
}
double Rectangle::GetLength()
{
    return length;
}
double Rectangle::GetArea()
{   
    return width*length;
}
double Rectangle::GetPerimeter()
{
    return 2*(width+length);
}
void  Rectangle::SetWidth(double myWidth)
{
   if(myWidth>0)
       width=myWidth;
}
void  Rectangle::SetLength(double myLength)
{
    if(myLength>0)
        length=myLength;
}
void main()
{
    Rectangle t1;
    double n,m;
    cout<<"please input width and length:\n";
    cin>>n;
    cin>>m;
    t1.SetWidth(n);
    t1.SetLength(m);
    t1.GetArea();
    t1.GetPerimeter();
    cout<<"width="<<t1.GetWidth()<<"\n"<<"length="<<t1.GetLength()<<"\n";
    cout<<"Area="<<t1.GetArea()<<"\n"<<"Perimeter="<<t1.GetPerimeter()<<"\n";
}
3 回复
#2
yuccn2012-11-09 12:47
class Rectangle
 {
 public:
     double GetWidth();
     double GetLength();
     double GetArea();
     double GetPerimeter();
     void SetWidth(double myWidth);
     void SetLength(double myLength);
     string GetColor();
     void SetColor(string clr);
 private:
     double length;
     double width;
     string color;
 };
 void Rectangle::SetColor(string clr)
 {
     color = clr;
 }
string Rectangle::GetColor()
{
     return color;
}


cout<<"GetColor="<<t1.GetColor().c_str();
#3
single0102032012-11-09 12:54
楼上最有一个cout<<"GetColor="<<t1.GetColor().c_str()中最后的c_str()啥意思啊?求解,谢谢,
#4
mmmmmmmmmmmm2012-11-09 14:56
函数声明:const char *c_str();
  c_str()函数返回一个指向正规C字符串的指针, 内容与本string串相同.

以下是引用single010203在2012-11-9 12:54:16的发言:

楼上最有一个cout<<"GetColor="<<t1.GetColor().c_str()中最后的c_str()啥意思啊?求解,谢谢,
1