将类引用传递给void函数会产生错误

时间:2022-04-07 20:59:54

I'm trying to pass a reference of a class through a void function, but it throws an error.

我试图通过void函数传递类的引用,但它会抛出一个错误。

Here is the code (it has to be a void function and not return anything). If I change the function to return int or string it works fine but I don't want to do that.

这是代码(它必须是一个void函数,不返回任何东西)。如果我将函数更改为返回int或string,它可以正常工作,但我不想这样做。

#include <iostream>
using namespace std;
class car
{
 public:

   car()
   : wheels(4)
   {
   }

   int wheels;
 };

 void getwheels(  car& i_car )
 {
   //do something here
 }

 int main()
 {
   car mycar;

   mycar.wheels = 6;

   cout << getwheels( mycar )<< endl;
}

The void is the problem.

空白是问题所在。

2 个解决方案

#1


2  

getwheels returns void, but you're printing it out as if it has a return value. If a function returns nothing, you can't print the result of calling it.

getwheels返回void,但是你将它打印出来就像它有一个返回值一样。如果函数没有返回任何内容,则无法打印调用它的结果。

To solve, just call the function without printing:

要解决,只需调用该函数而不打印:

getwheels( my_car );

Or if what you meant to do was print out the wheels value, print the value inside the function:

或者如果您打算打印出*值,请在函数内打印值:

void getwheels(car& i_car)
{
    cout << i_car.wheels << endl;
}

#2


1  

Try to return wheels from getwheels instead of void

尝试从轮圈返回*而不是空隙

int getwheels(const car& i_car)
{
  return i_car.wheels;
}

Or pass std::ostream into getwheels:

或者将std :: ostream传递给getwheels:

std::ostream& getwheels(std::ostream& out, const car& i_car)
{
  //do something here
  out << i_car.wheels << std::endl;;
  return out;
}

int main()
{
  car mycar;

  mycar.wheels = 6;

  getwheels(std::cout, mycar);
}

#1


2  

getwheels returns void, but you're printing it out as if it has a return value. If a function returns nothing, you can't print the result of calling it.

getwheels返回void,但是你将它打印出来就像它有一个返回值一样。如果函数没有返回任何内容,则无法打印调用它的结果。

To solve, just call the function without printing:

要解决,只需调用该函数而不打印:

getwheels( my_car );

Or if what you meant to do was print out the wheels value, print the value inside the function:

或者如果您打算打印出*值,请在函数内打印值:

void getwheels(car& i_car)
{
    cout << i_car.wheels << endl;
}

#2


1  

Try to return wheels from getwheels instead of void

尝试从轮圈返回*而不是空隙

int getwheels(const car& i_car)
{
  return i_car.wheels;
}

Or pass std::ostream into getwheels:

或者将std :: ostream传递给getwheels:

std::ostream& getwheels(std::ostream& out, const car& i_car)
{
  //do something here
  out << i_car.wheels << std::endl;;
  return out;
}

int main()
{
  car mycar;

  mycar.wheels = 6;

  getwheels(std::cout, mycar);
}