能够编译和运行.然而,当运行代码时,它不能打印我想打印的任何值
Able to compile and run. However, when runnig the code it can not print any value which i want to print
#include <typeinfo>
#include <iostream>
#include <math.h>
template <typename T>
class Polynomial
{
private:
Polynomial *termArray;
//int capacity;
//int terms;
T coef,exp;
public:
Polynomial()
{
termArray = new Polynomial[3];
};
~Polynomial();
void Print();
void CreateTerm(const T coef, const int exp);
};
template <typename T>
Polynomial<T>::~Polynomial()
{
delete []termArray;
}
template <typename T>
void Polynomial<T>::Print()
{
for(int i=0;i<3;i++)
std::cout << termArray[i].coef << " " << termArray[i].exp << std::endl;
}
template <typename T>
void Polynomial<T>::CreateTerm(const T coef,const int exp)
{
for(int i=0;i<3;i++)
{
termArray[i].coef = coef;
termArray[i].exp = exp;
}
}
int main()
{
Polynomial<double> f,g;
f.CreateTerm(-4.8,3);
f.CreateTerm(2.9,2);
f.CreateTerm(-3,0);
std::cout << "f = ";
f.Print();
g.CreateTerm(4.3,4);
g.CreateTerm(-8.1,0);
g.CreateTerm(2.2,3);
std::cout << "g = ";
g.Print();
return 0;
}
与前面的主题一样,该代码可以编译和运行。然而,当运行代码时,它不能打印任何值,我想打印出来,去长睡眠。(虽然我输入了任何东西,但它没有响应我的输入)
如何修改打印的代码…
这是你的构造函数:
Polynomial()
{
termArray = new Polynomial[3];
};
当你创建一个新的多项式时,你的代码会在构造函数中创建3个新的多项式。对于这3个多项式中的每一个,您将创建另外3个!在这一点上总共有13个多项式对象。新的再加3。这将一直持续下去,直到内存耗尽。更具体地说,当你用完堆栈空间时,因为这些都是在那里分配的。
你的代码永远不会超过这一行,因为它会递归地调用构造函数:termArray = new Polynomial[3];
其他需要考虑的事情:
- 考虑添加另一个类
Coefficient
。 而不是 - 一个多项式可以有多于或少于3个系数/指数。
- 如果你使用std::vector而不是数组,你可以简单地在你的类的
create_term()
中调用vector的push_back()
方法来添加一个新的系数。
Polynomial
对象内的Polynomial
对象的数组(相当字面上你的堆栈溢出错误),你会有一个Coefficient
对象的数组在你的Polynomial
对象。相关文章:
- 任何人都可以弄清楚这段代码如何显示运行错误?它打印无限时间 -1 以及正确答案
- 如何在运行时在对象数组中动态追加新对象C++并打印它们
- 为什么如果我从键盘输入EOF克里昂不要在运行窗口打印程序的输出?
- 在代码仍在 C++ QT 中运行时显示打印输出
- 为什么每次运行此程序时&x都会打印不同的值?
- GDB 在程序运行时打印文件名行号
- 我的 c++ 程序不打印任何字符,但是如果我将它们更改为 int,代码可以完美运行
- 尝试打印链表时出现运行时错误
- C++11 打印运行时变量名称等于某个 constexpr 变量
- 当我运行此C 程序时,销售名称1不会打印出来
- 程序运行,但程序中的第二个功能不打印?输出中没有错误
- 为什么当我运行此循环以打印字符串中的每个单词时,我缺少一个值
- 如何使用Qt Windows中的设置路径属性从命令行运行应用程序(.exe)时在命令行上打印日志
- Clang 运行时检查:打印回溯
- 尝试优化和理解打印数字除数的递归函数的运行时
- (可选)在运行时打印到标准输出
- 我希望程序打印数字 0 到 99,但是当我运行代码时,我看到 100 行 99
- 我正在尝试将 s1 中的所有字符更改为"x"。但是,当我运行代码时,编译器刚刚打印出"hello world"11次
- 我的程序将运行,但它会打印出所有 100 个值,这些值应该完全不同
- 如何通过Qt中的root特权以编程方式运行打印命令lpr-p