C ++ - 当被调用的函数具有参数时使用return

时间:2015-05-23 01:27:42

标签: c++ function parameters return

我有这样的功能:

void functiont(int a, int b)
{
        if(playingnumber=="T")
        {
            returntransfer=1;
            struct A
            {
                ~A() // Destructor to run after returning variable
                {
                    void cardselecth(int playingcolorh, int playingnumberh);
                }
            }
            return returntransfer;
        }
}

无论如何,我需要在不调用int a或int b的情况下获取返回的变量。所以我写的另一个函数

newvar=functiont(int a, int b);

它给出了编译错误。我不知道如何做到这一点。我可以写函数(a,b);我得到一个错误;我写函数(int,int);并得到一个错误。我试过写函数();但是它假设函数在同一个文件中并且我没有定义它,它不是(我在这里传输文件,所以我需要定义任何参数所以它知道引用另一个文件。)

2 个答案:

答案 0 :(得分:1)

如果您更喜欢返回int,则函数的返回类型应为int not void。我更正了代码如下。请注意带注释的更改

int functiont(int a, int b)
{
   int returntransfer=0; //change , declaration out of if block
                         // to maintain the scope of variable 
   if(playingnumber=="T")
        {
            returntransfer =1;

        }
        return returntransfer;//change
}

你可以在一个函数中声明一个struct变量,但它并不仅仅意味着它将被调用。

struct A
{
    ~A() // Destructor to run after returning variable
    {
       void cardselecth(int playingcolorh, int playingnumberh);
     }
};//change added ; at end of declaration.

修改 添加完整的程序以回答其他问题:

#include<iostream>
#include<string>

int functiont(int a, int b)
{
   int returntransfer=0; //change , declaration out of if block
                         // to maintain the scope of variable 
   std::string playingnumber ="T"; //Added again for completness
   if(playingnumber=="T")
        {
            returntransfer =1;

        }

    struct A
{
    ~A() // Destructor to run after returning variable
    {
       void cardselecth(int playingcolorh, int playingnumberh);
     }
};//change added ; at end of declaration.
        return returntransfer;//change
}

int main()
{
    std::cout<<functiont(2,3);
}

答案 1 :(得分:1)

我不确定你想做什么,但首先这个函数是一个void函数,因此它只能返回但不返回值。因此,您的签名或空格必须根据您要返回的类型进行更改。 在这种情况下

int functiont(int a, int b)

是合适的。

调用函数时,必须传递两个integer类型的参数。

newvar = function(1, 2);

发布错误也是一个好主意。最好的问候