gpt4 book ai didi

c++ - nullptr 不能在 valarray 中使用

转载 作者:行者123 更新时间:2023-11-30 02:33:22 25 4
gpt4 key购买 nike

为什么不能在构造函数中使用 nullptr?(函数名称:Wine)当我尝试这样做时,程序会崩溃并且没有任何错误报告可能是因为我不知道原因。

#ifndef WINE_H_
#define WINE_H_
#include<iostream>
#include<string>
#include<valarray>
using std::string;
using std::valarray;
template<typename T1, typename T2>
class Pair //member of the wine
{
private:
T1 a;
T2 b;
public:
T1 & first(){ return a; }
T2 & second(){ return b; }
T1 first()const{ return a; }
T2 second()const{ return b; }
Pair(const T1 & aval, const T2 & bval) :a(aval), b(bval){}
Pair(){}
};
typedef valarray<int>ArrayInt;
typedef Pair<ArrayInt, ArrayInt>PairArray;

class Wine
{
private:
string name;
PairArray bt;
int years;
public:
Wine();
Wine(const char * a, int y,int b[], int c[]); //no problem
Wine(const char * a, int y); //here is that problem function
void GetBottles(); //no problem
void Show()const; //no problem
int Sum(){ return bt.second().sum(); }
};

Wine::Wine(const char * a, int y) :name(a), years(y), bt(ArrayInt(0, y), ArrayInt(0, y)){}
**//When I am trying to use nullptr to instead 0 in the ArrayInt(0,y),the whole program will break down during work.**


Wine::Wine(const char * a, int y, int b[], int c[]) :bt(ArrayInt(b, y), ArrayInt(c, y))
{
name = a;
years = y;
}

Wine::Wine() :bt(ArrayInt(),ArrayInt())
{
name = "null";
years = 0;
}

void Wine::GetBottles()
{
std::cout << "Please input the years and the bottles\n";
for (int i = 0; i < years; i++)
{
std::cout << "input the year: ";
(std::cin >> bt.first()[i]).get();
std::cout << "input the bottles";
(std::cin >> bt.second()[i]).get();
}
}

void Wine::Show()const
{
using std::cout;
using std::endl;
for (int i = 0; i < years; i++)
{
cout << bt.first()[i] << '\0' << bt.second()[i] << endl;
}
}

#endif

#include<iostream> //test part
#include"wine.h"

int main(void)
{
using std::cin;
using std::cout;
using std::endl;

cout << "Enter name of wine: ";
char lab[50];
cin.getline(lab, 50);
cout << "Enter number of years: ";
int yrs;
cin >> yrs;

Wine holding(lab, yrs);
holding.GetBottles();
holding.Show();
return 0;

}

感谢您的帮助!

最佳答案

这很有趣。它在一个示例中中断但在另一个示例中没有中断的原因如下:

std::valarray 有两个不同的构造函数(不止于此,但这两个很重要):

valarray( const T& val, std::size_t count ); // 1
valarray( const T* vals, std::size_t count ); // 2

当您使用 0 (valarray(0, y)) 时,您正在调用第一个版本 - 创建一个 y 元素数组,其中每个元素都初始化为 0 .

但是当您使用 nullptr 调用它时,您正在调用它的第二个版本 - 尝试使用构造函数的第一个参数指向的数组的拷贝来初始化您的新数组。但是您的第一个参数是 nullptr,任何将 at 用作数组的尝试都会触发未定义的行为和程序崩溃。

关于c++ - nullptr 不能在 valarray 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35559039/

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