簡體   English   中英

C ++繼承的類函數在類構造函數中不起作用,通過引用字符串傳遞不改變

[英]C++ Inherited class function not working in class constructor, pass by reference string not changing

我有一個名為Filesys的類繼承了一個類Sdisk

class Sdisk
{
    public:
    Sdisk(string disk_name, int number_of_blocks, int block_size);
    Sdisk(); //default constructor
    ...
    int getblock(int blocknumber, string& buffer); //buffer is changed but doesn't change when called by Filesys constructor

    private:
    string diskname;    //file name of software-disk
    int numberofblocks; //number of blocks on disk
    int blocksize;  //block size in bytes

};

class Filesys: public Sdisk
{
    public:
    Filesys(string disk_name, int number_of_blocks, int block_size);
    Filesys(); //default constructor
};

我的Fileys構造函數從Sdisk類調用getblock並返回正確的值,但我的字符串緩沖區沒有改變

Filesys::Filesys(string disk_name, int number_of_blocks, int block_size) {
    string buffer;
    int code = getblock(0, buffer);

    if (code == 0) {  //passes this so it is calling the function and returning a value
        cout << "Failed"; 
    }

    cout << buffer; //empty, buffer is not being changed by getblock
}
//returns the blocknumber called for and passes it by ref in buffer
int Sdisk::getblock(int blocknumber, string &buffer){
    ifstream file(diskname);
    int i = (blocknumber -1) * blocksize;
    int j = (blocknumber * blocksize) -1;
    int k = 0;
    char b;

    if (j > (blocksize * numberofblocks)) {
        file.close();
        return 0;
    }

    while (file >> noskipws >> b) {
        if ((k > i-1) && (k < j+1)) {
            buffer.push_back(b);
        }
        k++;
    }
    file.close();
    return 1;

}

此函數在正常調用時起作用,例如

Sdisk disk1("test1",16,32);
string block3;
disk1.getblock(4, block3);
cout << block3; //correctly outputs what is being asked

為什么會發生這種情況?

Filesys的 ctor 應該將參數轉發給基類 ctor。
就像是:

Filesys::Filesys(string disk_name, int number_of_blocks, int block_size) 
     : Sdisk(disk_name, number_of_blocks, block_size) 
{
    // ...
}

否則基類的成員(例如diskname)沒有正確初始化, Sdisk::getblock需要它們才能正確運行。

您的函數 getBlock 使用 blockNumber == 0 調用

所以這些值會很奇怪。

int i = (blocknumber -1) * blocksize;
int j = (blocknumber * blocksize) -1;

i == -blocksize
j == -1

然后在你的 while 循環中,k 永遠不會小於 0 (j + 1)

if ((k > i-1) && (k < j+1)) {
   buffer.push_back(b);
}
k++;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM