C++中如何将指针传递给构造函数

how to pass pointer to constructor in c++

有一个派生的 class 需要一个指针作为基础 class 的构造函数。

你如何在 C++ 中做到这一点,我试过了,但它给了我一个错误。

#include <iostream>

using namespace std;

class Base {
protected:
    int *num;
public:
    Base(int *num);
    virtual void print();
};

Base::Base(int *num){
    this->num = num;
};

class Derived : public Base {
public:
    Derived(int *num) : Base(*num);
    void print();
};

Derived::print(){
    cout << "int value : " << *(this->num);
};

int main(){
    int num = 5;
    int *p = &num;
    
    Derived derived(p);
    derived.print();

    return 0;
}

Derived 构造函数初始化列表 中,您必须编写 Base(num) 而不是 Base(*num),如下所示:

Derived(int *num): Base(num) 
{
   //code here
}

请注意,您不必取消引用 指针num,而您在构造函数初始值设定项列表中使用它时正在这样做。当您取消引用 num 时,您会得到一个 int。因此,您将 int 传递给 Base 构造函数。