c++ buf()是什么?它到底做什么?

ubof19bj  于 2023-03-05  发布在  其他
关注(0)|答案(1)|浏览(212)

为什么这段代码在传递变量名给MyBuffer构造函数时使用buf()?buf()到底做什么?

#include <iostream>
using namespace std;

class MyBuffer {
private:
    int* myNums;

public:
    explicit MyBuffer(unsigned int length) {
        cout << "Constructor allocates " << length << " integers" << endl;
        myNums = new int[length];
    }
    ~MyBuffer() {
       cout << "Destructor releasing allocated memory"<< endl;
       delete[] myNums;
    }
};

int main() {
    cout << "How many integers would you like to store?" << endl;
    unsigned int numsToStore = 0;
    cin >> numsToStore;
    MyBuffer buf(numsToStore);
    return 0;
}

我对此做了一些研究,发现MyBuffer(numsToStore);实际上使编译器无法将numsToStore识别为MyBuffer的参数,而是将其识别为类似于以下内容的单独变量:要存储的我的缓冲区数;。解决这个问题的一个方法是添加buf(),但我不知道buf()的确切含义。

nnsrf1az

nnsrf1az1#

class不是对象,它是对象的 type

class MyBuffer {...}; //define a *type*
MyBuffer buf; //make an object of type `MyBuffer`, and name it `buf`.

class Person {...}; //define a *type*
Person Chanhyuk_Park; //make an object of type `Person` and name it `Chanhyuk_Park`.

但是,要创建对象,可能需要向其构造函数传递参数:

MyBuffer buf(numsToStore); //make an object of type `MyBuffer`, and name it `buf`.
//and pass the value `numsToStore` to its constructor

相关问题