繁体   English   中英

nullptr不能在valarray中使用

[英]nullptr can't use in valarray

为什么不能在构造函数中使用nullp?(函数名: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作为数组的尝试都会触发未定义的行为,程序崩溃。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM