编译器错误,提示对 something& 类型的引用初始化无效来自某物类型的表达*

2021-12-31 00:00:00 compiler-errors c++

我有一个像

test(something &)

我正在做

something *ss = new something();

我说

test(ss)

编译器抱怨说初始化了 something& 类型的引用from 表达 something * .

compiler complains saying initialization of reference of type something& from expression something * .

但不是 new 返回地址并且 ss 必须指向该地址!所以如果测试期待一个参考是不是它 ss 代表一个参考?

but isn't that new returns the address and ss must point to that address ! so if test is expecting a reference is not it ss represents a reference ?

推荐答案

你的函数需要一个普通的 something 对象.你不需要在这里使用指针:

Your function expects a normal something object. You don't need to use a pointer here:

something ss;

test(ss);

当您的函数签名看起来像 f(T&) 时,这意味着它接受对 T 对象的引用.当签名为f(T*)时,表示它接受一个指针到一个T对象.

When your function signature looks like f(T&), it means that it accepts a reference to a T object. When the signature is f(T*), it means that it accepts a pointer to a T object.

相关文章