gpt4 book ai didi

构造函数上的 C++ vector 释放

转载 作者:行者123 更新时间:2023-11-30 03:00:32 27 4
gpt4 key购买 nike

抱歉,我没有时间把它写出来,我希望我的解释足够透彻。我的一个类有一个 vector 作为私有(private)成员变量,它的大小在它的构造函数中声明。

现在,我从调试中发现,虽然 vector 确实在构造函数中分配了它的大小,但当构造函数返回时它会丢失所有大小(就好像它的内存分配只在构造函数的范围内一样,即使vector 是它的成员变量之一。它回到了一个空 vector)我需要我的 vector 在构造函数执行后保持它的大小,并且想知道我可以做些什么来解决这个问题,因为我初始化它的元素在我的其他函数之一中使用字符串。

附加评论中的内容

std::vector< std::vector< std::string > > routeInfo(
routeNum, std::vector< std::string >( 2 ) );

This is the vector's declaration in my constructor, routeNum is a variable which is initialized earlier in the constructor (initialized correctly, thats not the issue).

最佳答案

我必须根据您的代码假设您不知道如何在 C++ 中初始化成员变量。这是正确的方法:

class Myclass
{
// the declaration of the variable:
std::vector< std::vector< std::string > > routeInfo;

// declaration of the constructor:
Myclass(int routeNum);
};

// definition of the constructor
Myclass::Myclass(int routeNum)
: routeInfo(routeNum, std::vector< std::string >( 2 ))
{
// some other code
}

如果你简单地写:

Myclass::Myclass(int routeNum)
{
std::vector< std::vector< std::string > > routeInfo(
routeNum, std::vector< std::string >( 2 ) );
}

这将在构造函数中创建另一个隐藏原始变量的 routeInfo 变量。要访问成员变量,您必须编写 this->routeInfo 而不是 routeInfo 并且它的长度仍然为零。

关于构造函数上的 C++ vector 释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11905253/

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