【问题标题】:C++ Segmentation Fault Passing Class Variables to Class Functions将类变量传递给类函数的 C++ 分段错误
【发布时间】:2016-06-30 21:46:14
【问题描述】:

所以我试图有一个类变量,它是一个向量,并在一些类函数之间传递它。我正在尝试做的基本版本如下:

#include <iostream>
#include <string>
#include<stdlib.h>
#include <vector>
using namespace std;


class isingModel {
    private:
        int length;

    public:
        void set_values (int);
        void ising_Iterator(vector<vector<int> > & );
        vector<vector<int> >  lattice;
};


void isingModel::set_values (int l) {
    length = l;
    vector<vector<int> > lattice(length, vector<int>(length));

    for (int i=0;i<length;i++){
        for (int j=0;j<length;j++){
                int randNum = rand() % 2; // Generate a random number either 0 or 1
                lattice[i][j]=2*(randNum-.5); //shift value so that it is either 1 or -1.
        }
    }
}

void isingModel::ising_Iterator (vector<vector<int> > & lattice) {

    lattice[0][0]=1;

}



int main () {
    int L;
    cout << "Enter the length of the lattice: ";
    cin >> L;

    isingModel iModel;

    iModel.set_values(L);
    iModel.ising_Iterator(iModel.lattice );
    return 0;
}

所以我有一个有一些函数的类,但我的主要目标是制作一个类变量向量,然后将它传递给不同的类函数。在这段代码中,我制作了名为 lattice 的向量并将其值设置在 set_values 中,然后通过引用将 lattice 传递给 ising_Iterator 并希望更改 lattice 中的一些值。根据文档和其他问题,我认为我必须通过引用传递向量(因此函数声明中的 & )。但我似乎仍然遇到分段错误。用gdb发现问题出在ising_Iterator上,所以肯定是类函数ising_Iterator无权访问格向量。我很困惑的原因之一是,如果我更换

void isingModel::ising_Iterator (vector<vector<int> > & lattice) {

    lattice[0][0]=1;

}

void isingModel::ising_Iterator (vector<vector<int> > & lattice) {

    length=1;

}

一切都编译并运行良好。所以我得出的结论是,将作为向量的类变量传递给类函数并更改它们与将类变量传递给类函数并在那里更改它们有着根本的不同..

【问题讨论】:

    标签: c++11 vector segmentation-fault


    【解决方案1】:
    vector<vector<int> > lattice(length, vector<int>(length));
    

    你认为这是在做什么?它实际上做的是声明一个与成员变量同名的函数局部vector。这隐藏/隐藏成员,意味着您实际上是在更改本地范围的变量,而不是持久成员 - 因为“获胜”的重复名称是最近范围内的名称。

    因此,您正在更改方法 set_values() 中名为 lattice 的局部变量。根据定义,此类更改无法通过此功能实现。然后局部变量超出范围,没有被复制或以其他方式“发送”到任何地方,因此您对它的所有更改都是无关紧要的。

    您稍后尝试在方法 ising_Iterator() 中访问名为 lattice成员 变量,假设您已将 it 更改为非零大小,但失败因为你没有。索引时,繁荣:segfault。

    无论如何,您为什么认为必须在实例函数之间传递任何成员变量?所有方法都可以完全访问类成员。这就是......使用类的全部意义所在。在成员函数之间传递一个成员变量——虽然你的结论是错误的,如果处理得当它会正常工作——充其量是毫无意义的,最坏的情况是浪费资源。

    移除局部阴影,停止传递对成员的引用,直接在方法中使用成员变量。它会起作用的。

    【讨论】:

      猜你喜欢
      • 2014-04-03
      • 1970-01-01
      • 1970-01-01
      • 2017-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-15
      相关资源
      最近更新 更多