2013-04-03 47 views
0
#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); 
} 

我得到的输出是:不能在结构中创建球体1个实例

固体的描述表面积容积

我如何可以把一个一个数const函数通过常量引用并设置函数void而不返回任何东西?

+0

你能重新格式化你的问题吗?目前这是不可理解的...... – Synxis 2013-04-03 22:06:07

+0

你不能做你正在问的东西。通过参数获取返回值的唯一方法是如果参数由非const引用传递。 – 2013-04-03 22:07:10

+0

“sph”在哪里申报? – 2013-04-03 22:07:51

回答

2

您可以初始化连同您的全局变量的定义合并成一条线:

sphere_t sph = { 3 }; 
2

sph.radius = 3; 

是一个赋值语句,它分配的3至SPH值。半径。 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里面。