通过引用传递变量并构造新对象
Passing variables by reference and construct new objects
你好,我下面有这样的代码,我不知道为什么它不起作用。
class Clazz2;
class Clazz
{
public:
void smth(Clazz2& c)
{
}
void smth2(const Clazz2& c)
{
}
};
class Clazz2
{
int a,b;
};
int main()
{
Clazz a;
Clazz2 z;
a.smth(z);
//a.smth(Clazz2()); //<-- this doesn't work
a.smth2(Clazz2()); // <-- this is ok
return 0;
}
我有编译错误:
g++ -Wall -c "test.cpp" (in directory: /home/asdf/Desktop/tmp)
test.cpp: In function ‘int main()’:
test.cpp:26:17: error: no matching function for call to ‘Clazz::smth(Clazz2)’
test.cpp:26:17: note: candidate is:
test.cpp:5:7: note: void Clazz::smth(Clazz2&)
test.cpp:5:7: note: no known conversion for argument 1 from ‘Clazz2’ to ‘Clazz2&’
Compilation failed.
这是因为不允许非常量引用绑定到临时对象。另一方面,对const
的引用可以绑定到临时对象(参见C++11标准的8.3.5/5)。
您的第一个smth2
接受一个引用,该引用不能绑定到像您的构造函数调用a.smth(Claszz2())
那样的临时引用。但是,const引用可以绑定到临时引用,因为我们不能修改临时引用,所以它是允许的。
在C++11中,您可以使用右值参考,这样您就可以同时绑定临时值:
void smth2(Clazz2 &&);
int main()
{
a.smth(Claszz2()); // calls the rvalue overload
}
相关文章:
- Constexpr替代了新的放置方式,可以让内存中的对象保持未初始化状态
- 当一个新对象被分配到它的地址时,对象是否必须被销毁
- C++ 如何在将新对象分配给另一个对象时创建新对象
- 是什么让放置新调用对象的构造函数?
- 放置派生C++的新基子对象
- 重用对象与创建新对象
- 为指向C++中的对象/对象的指针分配堆内存
- thread_local 和 std::future 对象 - 对象的生存期是多少
- 使用矢量中的现有对象,如果C++中不存在,则创建新的对象
- 如何删除分配了新的对象
- C 将HEAP对象插入std ::用insert()插入映射,而另一个则存在删除新的对象
- 使用新的对象
- 使用C++0x std::thread调用新ed对象中的成员函数
- 新的新类对象的函数;错误:非静态成员引用必须相对于特定对象
- C++ 没有新返回对象的算术运算符
- 如何在每次迭代中创建一个新变量/对象的循环
- 如何在Cython中返回新的c++对象
- 如何在不'new'的情况下将新的对象实例添加到 std::list
- 使用“放置新”转移对象所有权
- 将两个复杂的属性重新组合成新的对象