【问题标题】:Class accepts unspecified initilizer [duplicate]类接受未指定的初始化程序[重复]
【发布时间】:2017-06-09 00:03:47
【问题描述】:

我不明白为什么 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

【问题讨论】:

    标签: c++ class c++11


    【解决方案1】:

    如果你想防止复制和赋值,只需删除那些方法:

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

    【讨论】:

    • 对不起,我应该澄清一下,我不明白为什么 init_test 的 intilisation 是有效的。
    • @Pax:有效,因为你没有使用我提供的代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-01
    相关资源
    最近更新 更多