c++ - 调用成员函数,在类外部声明

标签 c++ visual-studio-2010 function member-functions

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

'随机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.
};

请您帮我解决一下我哪里出错了。 非常感谢所有帮助

最佳答案

这里有两个问题。

首先,您调用m.random()——不存在这样的函数。您需要给它两个 int 参数。另外,由于它是静态,因此您根本不需要Random m;您可以使用Random::random(some_int, some_other_int);

其次,你有这个:

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

这里实际上有两个问题:首先,这不是函数调用,而是函数声明。函数声明的形式为 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
}

关于c++ - 调用成员函数,在类外部声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11853988/

相关文章:

c++ - 制作并重新编译带有子目录的 header

visual-studio-2010 - 如何在 Visual Studio 2010 中从 Ankhsvn 插件切换到 VisualHG

wpf - 由于网络上的 DLL,无法在 VS2010 中查看设计器

c++ - 从具有可变参数数量的函数调用具有可变参数数量的函数

c++ - 开发 C++ (Mingw) 堆栈限制

visual-studio-2010 - "Link Library Dependency"链接器选项在 Visual Studio 2010 - 2015 及更高版本中实际执行什么操作?

xcode - swift Xcode 6 : How do I use multiple functions in one statement?

php - 您如何自定义格式化 html 标记 MySQL 字段中的第一个单词/字符?

javascript - 通过函数返回 true 或 false,并按切片/间距 10 进行计算

c++ - 寻求帮助将 SOLID 原则应用于文件 I/O 问题