C++ 从另一个类返回的指针

C++ 从另一个类返回的指针,c++,C++,好的,在A班我有: int* attackerDice; int* defenderDice; 这两个变量调用另一个名为dice的类。因此: attackerDice = dice.roll() defenderDice = dice.roll() dice.roll的作用如下: int* Dice::roll () { int* ran = new int[1]; srand(time(NULL)); ran[0] = rand()%6+1; std::so

好的,在A班我有:

int* attackerDice;
int* defenderDice;
这两个变量调用另一个名为dice的类。因此:

attackerDice = dice.roll()
defenderDice = dice.roll()
dice.roll的作用如下:

int* Dice::roll () {
    int* ran = new int[1];
    srand(time(NULL));
    ran[0] = rand()%6+1;
    std::sort(ran,ran+1);
    return ran; 
}
namespace ex {
    class dice {
    private:
        std::mt19937 gen;
        std::uniform_int_distribution<> dis;
    public:
        dice(int to)
            : gen(std::random_device()())
            , dis(1, to)
            {}

        int roll() { return dis(gen); }
    };
}
现在我遇到的问题是attackerDice返回了-43249211234,而defender dice返回了正确的数字。我想这是因为我显然不明白什么时候使用*和&。有人能帮我吗

编辑:
如果我想要一个数组,我将如何进行这项工作?我想要它,这样我可以掷X个骰子

几乎所有关于代码的内容都是次优的:

  • 您正在使用动态分配,而实际上不需要
  • 您正在分配单个元素的数组并对其进行排序(顺便说一句,这毫无意义)
  • 您使用的是
    rand
    ,很久以来它一直被认为是“邪恶的”
  • 您正在放置的算法不使用类
    Dice
    的任何成员对象作为其成员函数之一
经修订的“理智”解决方案如下:

int* Dice::roll () {
    int* ran = new int[1];
    srand(time(NULL));
    ran[0] = rand()%6+1;
    std::sort(ran,ran+1);
    return ran; 
}
namespace ex {
    class dice {
    private:
        std::mt19937 gen;
        std::uniform_int_distribution<> dis;
    public:
        dice(int to)
            : gen(std::random_device()())
            , dis(1, to)
            {}

        int roll() { return dis(gen); }
    };
}
namespace-ex{
类骰子{
私人:
标准:mt19937 gen;
标准:均匀分布图;
公众:
骰子(整数到)
:gen(std::random_device())
,dis(1,to)
{}
int roll(){return dis(gen);}
};
}
然后将其用作类似于:

constexpr int count = 10;
std::vector<int> rolls;
rolls.reserve(count);

ex::dice dice(6);
std::generate_n(back_inserter(rolls), count, std::bind(&ex::dice::roll, dice));
constexpr int count=10;
std::向量卷;
3.储备(计数);
例:骰子(6);
std::generate_n(反向插入器(滚动),计数,std::bind(&ex::dice::roll,dice));

我的水晶球说,
骰子不服从

由于指针管理不善以及它们所指向的对象的生命周期,您似乎有未定义的行为

大多数情况下,C++不需要使用指针。 不要用C++编写

new

请参阅Jeffrey的答案,了解如何避免终身问题

好多了。警告:在循环中每次实例化一个新的随机生成器是非常不理想的,使用这样的均匀分布是有缺陷的。相反,要:

auto dice = bind(uniform_int_distribution<>(1,6), mt19337 { random_device{}() });

只要使用相同的
骰子
对象,它实际上是均匀分布的

为什么要用一个元素对数组进行排序?为什么要动态分配一个
int
?这样会占用更多内存,容易出错,并且比只返回
int
要慢。为什么要用单个元素对数组进行排序?
std::sort(ran,ran+1)嗯?这样做的目的是什么?您正在尝试使用单个元素对数组进行排序?糟糕。很抱歉,我正在实现它,以便我可以滚动任意数量的骰子,并且它将从最大的骰子返回到最小的骰子。不过我还没讲完。非常好的笔记。我从我的回答中引用了你的例子。但是,像这样使用
仍然存在一些问题+谢谢你的解释。非常感谢。我对C++仍然很陌生,所以我没有线索兰德被认为是“邪恶的”。到目前为止,我主要是用java编程,所以我还在学习这门语言。用一个int数组而不是一个普通的int数组能很好地完成这项工作吗?这样我就可以一次掷多个骰子了?那一行
dice
对象真是太聪明了。@。这里真正的问题是
dice
的单数实际上是
die
,函数应该是
int roll1=die()
。哈哈哈。那很有趣