C ++ - 在另一个函数中使用的返回值

时间:2014-01-22 22:51:42

标签: c++

我在使用其他函数的返回值时遇到问题。以下是一些细节:

Class1.cpp:

Double Class1::SetValue (double value2)
{
    // method code
    Return value_set;
}

Class2.cpp:

Void Class2::CountValue(double a)
{
    Class1 *object1;
    Double value_received= object1->SetValue(object1->value2)
    // do something with value_received
}

问题是我需要在Class2的CountValue中使用SetValue中的value_set。上面的代码给了我错误:

Unhandled exception at 0x6462696c in xxx.exe: 0xC0000005: Access violation.

请帮帮我吗?

2 个答案:

答案 0 :(得分:3)

SetValue来电中,您传递的参数为object1->value2。但是你还没有设置指针object1,它仍然没有初始化。这是未定义的行为。你很幸运它崩溃了,或者你可能更难找到它。

答案 1 :(得分:0)

有几个问题。将变量初始化为某个函数的返回值应该没有问题。我们一直这样做,即使你通常不会看到像算术运算符或按位运算符这样的典型函数调用。

使用您的功能

double Class1::SetValue(double value2)
{
  //generally you are setting some variable that is a part of Class1
  this->value = value2;

  //if you are returning something you might want to have some error code 
  //just in case something went wrong, but it looks like you are just
  //returning the number that you are sending in as a parameter.

  return value2;  
}

我不确定你的下一个功能会发生什么,但我们可以剖析它。

void Class2::CountValue(double a)
{
    Class1 *object1;//this is a pointer to an object, not an instance of an object

    //                       object1 is not initialized so you cannot
    //                       use object1->value2 even if it is set in
    //                       your default constructor

    double value_received = object1->SetValue(object1->value2);
    // do something with value_received
}

为了让您的代码正常工作,您可能希望将其更改为

void Class2::CountValue(double a)
{
  Class1 object1;//not a pointer to Class1 anymore

  // This will work if object1.value2 is set in the default constructor

  double value_received = object1.SetValue(object1.value2);
  // do something with value_received
}

或者如果您尝试同时设置value_recieved和object1.value2,我们可以

void Class2::CountValue(double a)
{
  Class1 object1;//not a pointer to Class1 anymore

  double value_received = object1.SetValue(12.2);
  // do something with value_received
}