2012-08-07 79 views
2

我想调用'int Random :: random(int lower,int upper)函数,但是我得到一个问题,说'成员函数不能在类之外重新声明'我也尝试提供以下形式的解决方案:调用成员函数,在类之外声明

'Random m; m.Random()”

这下面要说的问题 '在函数调用太少参数'

下面是main.cpp的文件

#include <iostream> 
#include <cstdlib> 
#include <ctime> 
using namespace std; 

#include "Circle.h" 
#include "Random.h" 

int main() 
{ 
    Random m; 
    m.random(); 

    // Array 1, below section is to populate the array with random 
    // radius number within lower and upper range 
    int CircleArrayOne [5]; 
    const int NUM = 5; 

    srand(time(NULL)); 

    for(int x = 0; x < NUM; ++x) 
    { 
     int Random::random(int lower, int upper); 
    } 

    // output the radius of each circle 
    cout << "Below is the radius each of the five circles in the second array. " << endl; 

    // below is to output the radius in the array 
    for(int i = 0; i < NUM; ++i) 
    { 
     cout << CircleArrayOne[i] << endl; 
    } 

    system("PAUSE"); 
    return 0; 
} 


int Random::random(int lower, int upper) 
{ 
    cout << "Enter lower number: " << lower << endl; 
    cout << "Enter upper number: " << upper << endl; 

    int range = upper - lower + 1; 
    return (rand() % range + lower); 
} 

下面是Random.h文件

#pragma once 
#include <iostream> 
#include <cstdlib> 
#include <ctime> 
using namespace std; 

class Random 
{ 
public: 
    static void initialiseSeed(); 
    // random number initialised 
    // random number has been initialised to the current time. 

    static int random(int lower, int upper); 
    // this function will return a positive random number within a specific lower and 
    // upper boundary. 
}; 

请问您能帮我解决问题吗? 所有帮助是非常赞赏

回答

2

这里有两个问题。

首先,您致电m.random() - 不存在此功能。你需要给它两个int参数。另外,因为它是static,所以根本不需要Random m;你可以使用Random::random(some_int, some_other_int);

其次,你有这样的:

for(int x = 0; x < NUM; ++x) 
{ 
    int Random::random(int lower, int upper); 
} 

这里包括两个问题:第一,这是不是一个函数调用,它是一个功能declaraction。函数声明的格式为return_type function_name(arg_type arg_name /* etc. */);,就像你在这里一样。要调用它,你只需要传递实际值,而不包括返回值 - 这就是它会给你的。其次,你需要实际存储结果的某个地方。您的评论表明这应该是CircleArrayOne,但实际上并没有像您声称的那样填充它。

试试这个:

for(int x = 0; x < NUM; ++x) 
{ 
    CircleArrayOne[x] = Random::random(0, 10); // assumed 0 and 10 as the bounds since you didn't specify anywhere; you could use variables here also 
} 
2

原型:

static int random(int lower, int upper); 

您的来电:

Random m; 
m.random(); 

您也需要为他们提供的参数,或者一些默认值。另外,由于该方法是static,因此不需要实例来调用它。

Random::random(0,100) 

就够了。

即使是评论暗示这一点:

// this function will return a positive random number within a specific lower and 
// upper boundary. 

您提供既没有下也不上限。

0

什么错的是你有语法调用函数错了,这是不一样的语法来声明函数。如果你想调用一个函数,你给出函数的名字,然后是parens。并且在你的父亲之间,你需要提供任何参数。你可能想用函数的返回值做一些事情。现在我并没有真正遵循你想要做的事情,但是这样的事情可能就是你正在寻找的东西。

int result = Random::random(1, 10); 

使然后命名功能Random::random,其次是在这种情况下的参数,1和10的,你可能会想改变这些值。在这种情况下,我从函数调用中获取返回值并将其分配给名为result的变量。你可能想要改变它。

这将在任何关于C++的书中都涵盖,可能值得投资于其中之一。