函数从指针 c++ 中获取错误的值并返回错误的答案

Function takes wrong values from pointers c++ and returns wrong answer

本文关键字:错误 答案 返回 取错误 指针 c++ 获取 函数      更新时间:2023-10-16

我刚开始学习编程,遇到了一些麻烦。这是我正在尝试做的:

  1. 使用构造函数创建一个新类;
  2. 将用户的两个数字写入类对象;
  3. 使用此类函数获取两个数字的总和;

但是由于某种原因,类函数采用一些奇怪的数字而不是类对象(我正在沿路检查它们(。

#include "pch.h"
#include <iostream>
#include <string>
using namespace std;
class math_function {
public:
string function_string;
double function_result;
};
class binary_operation : public math_function {
public:
double* argument_1;
double* argument_2;
};
class sum : public binary_operation {
public:
sum(double arg1, double arg2) {
this->argument_1 = &arg1;
this->argument_2 = &arg2;
cout << *this->argument_1 << " INSIDE CONSTR " << *this->argument_2 << "n";
}
double evaluate() {
cout << *this->argument_1 << " pointers " << *this->argument_2 << "n";
this -> function_result = *this->argument_1 + *this->argument_2;
return function_result;
}
};
int main(int argc, string argv)
{
cout << "enter two nubmersn";
double arg1, arg2;
std::cin >> arg1;
std::cin >> arg2;
sum* sum1 = new sum(arg1, arg2);
double result = sum1->evaluate();
cout << "n" << result;
system("Pause");
}

以下是控制台的输出:

enter two numbers
29
13
29 INSIDE CONSTR 13
-9.25596e+61 pointers 1.23419e-305
-9.25596e+61

我做错了什么?

这个

this->argument_1 = &arg1;       // NO 

与你想做的有点相反。您正在将指针成员设置为构造函数本地的arg1地址。在您尝试打印值时,arg1早已消失。如果有的话,你想要

*(this->argument_1) = arg1;     // still NO

这会将arg1的值分配给doubleargument_1指向的。但是,您从未分配过double,因此argument_1没有指向双精度。取消引用无效指针是未定义的行为!

干脆不要使用指针。最好使用初始值设定项列表...

struct binary_operation : public math_function {
double argument_1;
double argument_2;
binary_operatotion(double arg1,double arg2) : argument_1(arg1),argument_2(arg2) {}
};
struct sum : public binary_operation {
sum(double arg1, double arg2) : binary_operation(arg1,arg2) {}
};

您将传递给构造函数的两个参数的地址(按值(存储在参数 1 和 2 中。 一旦你退出函数,这些地址就不再有意义了(是的,构造函数(也是(一个函数。

你有不同的选择。 首先是将参数作为指针传递,而不是复制值

sum(double* arg1, double* arg2) {
this->argument_1 = arg1;
this->argument_2 = arg2;
cout << *this->argument_1 << " INSIDE CONSTR " << *this->argument_2 << "n";
}

但实际上,在你的情况下,你根本不需要指针:只需将参数存储为double,而不是double*

class binary_operation : public math_function {
public:
double argument_1;
double argument_2;
};

并更改所有代码以使用double而不是double*(很简单,编译器将帮助您在旧代码不再有效的情况下引发错误(