常量对象



定义一个类Shape,并从至少有一个常量数据成员的类中创建常量对象。从类Shape在主函数中创建对象。同时在主((功能中显示恒定对象的状态

#include <iostream>
using namespace std;
class Shape
{
private:
string color;
const float radius;
public:
Shape(string,float);
};
Shape:: Shape(string clr,float rad): radius(rad)
{
color = clr;
cout<<"The color of the  Shape(Circle) is : "<<clr<<endl<<"The radius is : "<<radius<<endl;
}
int main()
{
const Shape sh("Red", 7.5);
return 0;
}

上面的代码是否满足上面的问题?

我不会在构造函数中打印输出,而是创建一个print函数,然后从main调用它。

构造函数应该初始化对象。它的打印是由该类的用户或该类的某些函数完成的,具体取决于需求。

#include <iostream>
using namespace std;
class Shape
{
private:
string color;
const float radius;
public:
Shape(string,float);
void Display(void)const;
};
Shape:: Shape(string clr,float rad):color(clr), radius(rad) {}
void Shape:: Display(void)const
{
cout<< "The color is : "<<color<<endl;
cout<< "The radius is : "<<radius<<endl;
}
int main()
{
const Shape sh("Red",7.8);
sh.Display();
return 0;
}
enter code here

最新更新