abstract class CAbstract
{
private string mParam1;
public CAbstract(string p开发者_如何转开发aram1)
{
mParam1 = param1;
}
}
class CBase : CAbstract
{
}
For the class CBase, it should be initialized by providing the parameter, so how to disable the parameterless constructor for CBase class?
If you define a parameterized constructor in CBase
, there is no default constructor. You do not need to do anything special.
If your intention is for all derived classes of CAbstract
to implement a parameterized constructor, that is not something you can (cleanly) accomplish. The derived types have freedom to provide their own members, including constructor overloads.
The only thing required of them is that if CAbstract
only exposes a parameterized constructor, the constructors of derived types must invoke it directly.
class CDerived : CAbstract
{
public CDerived() : base("some default argument") { }
public CDerived(string arg) : base(arg) { }
}
To disable default constructor you need to provide non-default constructor.
The code that you pasted is not compilable. To make it compilable you could do something like this:
class CBase : CAbstract
{
public CBase(string param1)
: base(param1)
{
}
}
Please correct me if I am wrong, but I think I achieved that goal with this code:
//only for forbiding the calls of constructors without parameters on derived classes
public class UnconstructableWithoutArguments
{
private UnconstructableWithoutArguments()
{
}
public UnconstructableWithoutArguments(params object[] list)
{
}
}
精彩评论