gpt4 book ai didi

c++ - 我的模板类返回了错误的数据

转载 作者:行者123 更新时间:2023-11-27 22:50:25 26 4
gpt4 key购买 nike

所以当我运行我在下面写的程序时,打印出来的是

What is passed in 4 7
What is inside -1138187264 32566
-1138187264 + 32566 = -1138154698
1
0

我需要它保存 4 和 7 而不是它当前保存的垃圾数字。我认为我没有错误地传递我的值(value)观。我试图取消对它们的引用,但这也没有用。我只想让我的类(class)计算器保存 2 个整数。但是出于某种原因,当我输入数字时它无法识别它们?我不太确定这里发生了什么。

这是我的主课

#include <stdlib.h>
#include <iostream>
#include "Calculator.h"
#include "Calculator.cpp"
using namespace std;

class Arithmetic {
private:
int intData;
public:
Arithmetic() {
intData = 0;
}
Arithmetic(int i) {
intData = i;
}
void intOperations(Arithmetic obj) {
cout << "What is passed in " << intData << " " << obj.intData << endl;
Calculator<int> cint(intData, obj.intData);
cout << "What is inside " << cint.getValue1() << " " << cint.getValue2() << endl;
printOperations(cint);
}
};

int main(){
// Create 1st object
int int1 = 4;
Arithmetic arith1(int1);
// Create 2nd object
int int2 = 7;
Arithmetic arith2(int2);
arith1.intOperations(arith2);

}

这是我的 calc.h 头文件

#ifndef CALCULATOR_H
#define CALCULATOR_H

template <class T>
class Calculator {
private:
T value1;
T value2;
public:
Calculator();
Calculator(T value1, T value2);
T getValue1();
T getValue2();
T getSum();
int getLogicalAND();
bool isGreater();
};

#endif

这是我的 calc.cpp 类

#include "calc.h"
template <class T>
Calculator<T>::Calculator(){
value1 = T();
value2 = T();
}

template <class T>
Calculator<T>::Calculator(T value1, T value2) {
value1 = value1;
value2 = value2;
}

template <class T>
T Calculator<T>::getValue1() {
return value1;
}

template <class T>
T Calculator<T>::getValue2() {
return value2;
}

最佳答案

当你写的时候:

template <class T>
Calculator<T>::Calculator(T value1, T value2) {
value1 = value1;
value2 = value2;
}

您正在混合函数参数和类属性....在编译器优化之后(因为当您编写 value1 = value1;...您实际上什么也没做...),您最终得到等同于:

template <class T>
Calculator<T>::Calculator(T value1, T value2) {
}

因此 value1value2 未初始化...这是垃圾。

你需要做的:

template <class T>
Calculator<T>::Calculator(T value1, T value2) {
this->value1 = value1;
this->value2 = value2;
}

更好的是,使用初始化列表:

template <class T>
Calculator<T>::Calculator(T value1, T value2) :
value1(value1),
value2(value2)
{
}

关于c++ - 我的模板类返回了错误的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37645601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com