gpt4 book ai didi

C++:我可以强制我的程序员为每个类定义复制构造函数吗?

转载 作者:太空狗 更新时间:2023-10-29 23:20:58 25 4
gpt4 key购买 nike

我可以强制我的程序员为每个继承自基类的类定义复制构造函数吗?可以实例化基类。

我是说如果我有

class A {
public
A(const A&);
};

class B : public A {
public
B(const B&); // I want to force my programmers to write this line, any idea????
};

最佳答案

也许答案就在CRTP中.

我现在能想到的最接近的解决方案是一个伪基础和一个带有私有(private)抽象 copy_construct 函数的 CRTP,以提醒程序员。

template <class Derived>
class Base {
private:
virtual void copy_construct(const Derived& d) = 0;

//btw; unfortunately this isn't possible:
//virtual Derived(const Derived& b) = 0;
};

class PseudoBase : public Base<PseudoBase>
{
public:
PseudoBase() {};
PseudoBase(const PseudoBase& pd)
{
copy_construct(pd);
}

private:
void copy_construct(const PseudoBase& rhs)
{
//copy code
}
};

class Derived : public Base<Derived>
{
//Programmer forgot about copy constructing

};

int _tmain(int argc, _TCHAR* argv[])
{
PseudoBase pb0;
PseudoBase pb1 = pb0;

Derived d0;
Derived d1 = d0;

return 0;
}

构建将失败:

1>d:\source\test\test\test\test.cpp(42): error C2259: 'Derived' : cannot instantiate abstract class
1> due to following members:
1> 'void Base<Derived>::copy_construct(const Derived &)' : is abstract
1> with
1> [
1> Derived=Derived
1> ]
1> d:\source\test\test\test\test.cpp(9) : see declaration of 'Base<Derived>::copy_construct'
1> with
1> [
1> Derived=Derived
1> ]

关于C++:我可以强制我的程序员为每个类定义复制构造函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11207402/

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