【问题标题】:Runtime Error in using function call by reference?通过引用使用函数调用时出现运行时错误?
【发布时间】:2013-06-04 07:10:58
【问题描述】:

我有一个类定义为,

class dimension{
public:
    dimension();
    const char* getname();
    long ing getlength();
    void setname(const char* text)
    void setlength(long int size)
    virtual ~dimension();
private:
    const char* name;
    long int length;
}

我收到关于函数setnamesetlength 的错误很重要,因此它们的定义如下,

void dimension::setname(const char* text)
{
    dimension::name = text;
}
void dimension::setlength(long int size)
{
    dimension::length = size;    
}

现在我有 2 个函数用于从文件中读取类维度的对象数组。他们的定义是as。

void read_dimension(dimension** dims, int*ndims, const char* text, long int size)
{
    int i;
    *dims = new dimension[*ndims];
    for(i=0; i<ndims; i++)
    {
        (*dims)[i].setname(text)   
        (*dims)[i].setlength(size) 
    }
}

void read_file(char *path, dimension** dims, int *ndims)
{
    //do-- open file and read the variables ndims, text and size from it.
    read_dimension(dims, ndims, text, size);
    //do-- print name and length of all elements of (*dims).
}

现在,我在 ma​​in 中将这些函数称为

int main()
{
    //do-- get file path
    dimesnion* gdims;
    int num_dims;
    read_file(path, &gdims, &num_dims);
    //do-- print name and length of each element of gdims.
    return 0;
}

当我运行代码时,从函数 read_dimension()main() 打印的变量 "name" 是不同的,但变量 "length" 是相同的。
我不知道为什么会这样.
如果有人能提供帮助,我会很高兴。

【问题讨论】:

  • 函数 read_dimension 中声明的文本在哪里?
  • 您发布的read_dimension 似乎被截断了。特别是,变量text 来自哪里?注意name只是一个char指针,所以如果你在离开read_dimension之后删除底层数组,name将指向垃圾。
  • 为什么不改用std::stringstd::vector
  • 您发布的代码无法编译。请发布 SSCCE (sscce.org)
  • @ComicSansMS,好的,有问题了...当我离开函数 read() 时,指向 name 的指针被删除,谢谢...!!

标签: c++ class pointers


【解决方案1】:

毫无疑问,text 是 read_dimension 函数中的一个局部变量,可能是一个 char 数组。 dimension::setname 将一个指针分配给另一个指针,如前所述,当 read_dimension 函数中的文本变量超出范围时会发生什么?它会死的......现在你在维度类中的指针指向“无处”。 我更喜欢使用 const char * 作为字符串文字或作为指向字符数组中某个字符的指针。如果你想存储一个字符串,你可能会通过 strcpy 复制它,当然必须存在具有足够空间的 char 目标数组。

这段代码的目的是什么:dimension::name = text;和尺寸::长度=尺寸;在 setname 和 setlength 方法中?你在维度类的范围内,不是吗?

【讨论】:

  • 谢谢,一旦我超出 read_dimension 的范围,指针指向无处,我就遇到了问题。关于另一件事,我使用变量名“名称”和“长度”而不是文本和大小,所以为了我自己的清楚,我写了维度::名称=名称
  • 我明白了。此外,如果某些成员被参数隐藏,您可以在非静态方法中使用此指针来访问它们。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-24
  • 1970-01-01
  • 2015-07-21
相关资源
最近更新 更多