gpt4 book ai didi

引用结构的c++类构造函数

转载 作者:行者123 更新时间:2023-11-28 03:34:30 25 4
gpt4 key购买 nike

我有一个类打印机

class Printer{
struct foo{
int i;
};
foo & f;
};

当我调用 Printer 的构造函数时,我需要初始化 f,因为 f 是一个引用,但我想要的是首先调用 foo 的构造函数并创建它的一个实例,然后将它分配给 f。我遇到的问题是如果我打电话

Printer::Printer():f(foo(0)){ }

有一个错误说我不能使用对结构的临时实例的引用。有办法解决这个问题吗?

谢谢

最佳答案

在这种情况下引用没有任何意义。请尝试以下操作:

class Printer{
struct foo{
int i;
foo(int i_) : i(i_) {} // Define a constructor
};

foo f; // Not a reference anymore!

public:
Printer::Printer() : f(0) {} // Initialise f
};

关于引用结构的c++类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11441095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com