【发布时间】:2013-11-19 09:27:33
【问题描述】:
今天我在将 std::unique_ptr 传递给函数/重载运算符时遇到问题。例如:
HEADER
class SpaceMarine{
public:
...
friend std::ostream & operator << (std::ostream &exit, const SpaceMarine &SM);
private:
std::string name_;
.... (some other few parameters)
std::unique_ptr<armor> armor_;
在 .cpp 中我得到了:
std::ostream & operator << (std::ostream &exit, const SpaceMarine& SM){
exit << ... << *SM.stats_ << !!!!!! << *SM.weapon_;
return exit;
}
stats_ 和 Weapon_ 都是通过指针作为主类成员的类。 对于所有类,它们自己的重载运算符 >> 和
std::cout << armor1;
or
std::cin >> weaponb;
他们工作)。
所以:我必须用什么代替!!!!!! , 为了使 unique_ptr 以与 *SM.stats_ 类似的方式工作?所以它指向了armor类的重载运算符,并在主类的重载运算符中使用它?
编辑
对于迈克西摩:
std::ostream & operator << (std::ostream &exit, const Armor& arm){
return exit << "\n" << arm.name_ << " AR: " << arm.toughness_;
}
但是,正如我之前写的 - 成员类(Armor,Weapon)的重载运算符有效。
【问题讨论】:
-
智能指针可以像普通指针一样使用,例如
*armor_如果是“普通”指针或智能指针,其工作方式相同。参见例如std::unique_ptr::operator*. -
那么是
armor还是Armor?您有两种不同的类型,还是一种是复制/粘贴错误?如果您提供一个完整(但很小)的示例来确切说明在您尝试输出*armor_时出了什么问题以及完整的错误消息,那么这个问题会更容易回答。
标签: c++ function smart-pointers