无法在结构中创建 1 个球体实例
Can't Create 1 instances of sphere in structs
#include <iostream>
#define _USE_MATH_DEFINES
#include <math.h>
using namespace std;
//the volume and surface area of sphere
struct sphere_t { float radius; };
sphere_t sph;
sph.radius = 3; // this is the part that mess me up, error in sph.radius
double SphereSurfaceArea(const sphere_t &sph)
{
return 4*M_PI*sph.radius*sph.radius;
}
double SphereVolume(const sphere_t &sph)
{
return 4.0/3.0*M_PI*sph.radius*sph.radius*sph.radius;
}
int main()
{
cout << "Sphere's description: " << sph.radius << endl;
cout << "Surface Area: " << SphereSurfaceArea(sph) << endl;
cout << "Volume :" <<SphereVolume(sph) << endl;
system("pause");
return(0);
}
我得到的输出是:
固体的描述表面积体积
我怎么能把一个数字在常量引用的const函数和设置函数void不返回任何东西?
您可以将初始化与全局变量的定义合并为一行:
sphere_t sph = { 3 };
This
sph.radius = 3;
是一个赋值语句,它将值3赋给sph.radius。c++的一个规则是,赋值语句只能在函数中使用。你在函数外写了一个。
我会这样写你的代码
int main()
{
sphere_t sph;
sph.radius = 3;
cout << "Sphere's description: " << sph.radius << endl;
cout << "Surface Area: " << SphereSurfaceArea(sph) << endl;
cout << "Volume :" << SphereVolume(sph) << endl;
system("pause");
return(0);
}
现在赋值(和sph的声明)在函数main中
相关文章:
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 如何创建一个空的全局类并在启动时实例化它
- 无法创建抽象类的实例
- 为什么创建友元类的实例会导致"undefined reference to"错误?
- 在C++中为链表类创建实例
- 如何为类的每个实例创建特定实例的方法
- 基于现有实例创建类的新实例
- 从模板类的另一个实例创建模板类的实例时省略模板参数
- Vulkan-加载扩展时实例创建失败
- 通知B1或B2或B3类的特定实例创建Pointer A类
- 使用std::shared_ptr对象实例创建boost::线程
- 如何在C++中仅包含一个实例创建类
- 如何从旧实例创建新实例
- 在V8 javascript引擎中,如何为每个实例创建一个重新使用ObjectTemplate的构造函数
- 有没有一种方法可以从基本实例创建派生实例
- 如何在修改设计时停止现有代码基类的实例创建
- 使用基类实例创建派生类实例
- 如何从另一个仅静态选择满足特定类型规则的索引的元组实例创建元组实例