Class接受未指定的initilizer

时间:2017-06-09 00:03:47

标签: c++ class c++11

我不明白为什么Item_Base的初始化程序接受另一个对象作为有效输入。我假设这里使用了一些隐式重载?

class Item_Base 
{
public:
  Item_Base(const std::string& item_name);
  ~Item_Base(void);
  std::string tostr();
private:
  const std::string name;
};

Item_Base::Item_Base(const std::string& item_name)
:name(item_name)
{
  std::cout << "Constructing: " << name << std::endl;
}

Item_Base::~Item_Base(void)
{
  std::cout << "Destructing: " << name << std::endl;
}

std::string Item_Base::tostr()
{
  return name;
}

int main(int argc, char **argv)
{
  Item_Base red_book("Red Book");
  Item_Base green_bow("Green Bow");
  Item_Base copy_test = red_book;
  Item_Base init_test(green_bow); // Why does this work?

  std::cout << red_book.tostr() << std::endl;
  std::cout << green_bow.tostr() << std::endl;
  std::cout << copy_test.tostr() << std::endl;
  std::cout << init_test.tostr() << std::endl;

  return 0;
}

输出

Constructing: Red Book
Constructing: Green Bow
Red Book
Green Bow
Red Book
Green Bow
Destructing: Green Bow
Destructing: Red Book
Destructing: Green Bow
Destructing: Red Book

1 个答案:

答案 0 :(得分:0)

如果您想阻止复制和分配,只需删除这些方法:

Item_Base(const Item_Base&) = delete;
Item_Base& operator=(const Item_Base&) = delete;