gpt4 book ai didi

c++ - 如何防止实现一个打算在 C++ 中不实现的方法?

转载 作者:可可西里 更新时间:2023-11-01 15:45:56 29 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
What's the most reliable way to prohibit a copy constructor in C++?

假设我想让一个类不可复制并且想要 prohibit copy constructor and assignment operator .我将它们设为私有(private)并保留未实现:

class Class {
//useful stuff, then
private:
Class( const Class& ); //not implemented anywhere
void operator=( const Class& ); //not implemented anywhere
};

这样,如果它们中的任何一个被 friend 或同一个类中的意外调用,我就会收到链接时错误。

现在如果用户实现它们会怎样?我的意思是没有实现,所以任何人都可以添加自己的:

Class::Class( const Class& )
{
//whatever they want
}

当然,我可以创建自己的实现并在其中添加一个断言,但这会延迟意外调用检测,直到程序运行为止。

有没有一种方法可以防止用户实现这种方法,并且仍然可以在编译时检测到对它们的意外调用?

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com