[英]When does a class not contain a constructor?
I'm quite new to C++, but have general knowledge of other languages. 我是C ++的新手,但对其他语言有一般的了解。 Lately I've seen some tutorials about C++, and I have sometimes seen classes that do not have their own constructor, not even className();
最近我看过一些关于C ++的教程,我有时看到的类没有自己的构造函数,甚至没有className();
. 。 This might exist in the other languages as well, but I've never seen it before. 这可能也存在于其他语言中,但我以前从未见过它。 I don't think I've seen them in use before either, so my question is: what are they for? 我不认为我之前已经看过它们,所以我的问题是:它们适用于什么? And what are they? 他们是什么? I tried googling this, but I don't know the name for it.. 'constructorless class' didn't give me much. 我试过谷歌搜索这个,但我不知道它的名字..'无构造类'并没有给我太多。
Without a constructor, is it possible to instantiate it? 没有构造函数,是否可以实例化它? Or is it more of a static thing? 或者它更像是一个静态的东西? If I have a class that contains an integer, but has no constructor, could I go int i = myClass.int;
如果我有一个包含整数但没有构造函数的类,我可以去int i = myClass.int;
or something like that? 或类似的东西? How do you access a constructorless class? 你如何访问无构造函数的类?
If you don't explicitly declare a constructor, then the compiler supplies a zero-argument constructor for you. 如果没有显式声明构造函数,那么编译器会为您提供零参数构造函数。 * *
So this code: 所以这段代码:
class Foo {
};
is the same as this code: 与此代码相同:
class Foo {
public:
Foo() {};
};
If you do not specify a constructor explicitly compiler generates default constructors for you (constructor without arguments and copy constructor). 如果没有指定构造函数,则编译器会为您生成默认构造函数(不带参数的构造函数和复制构造函数)。 So there is no such thing as constructorless class. 所以没有无构造类的东西。 You can make your constructor inaccessible to control when and how instances of your class created but that's a different story. 您可以使构造函数无法访问,以控制何时以及如何创建类的实例,但这是一个不同的故事。
A class without a constructor is a good model for implementing an interface. 没有构造函数的类是实现接口的好模型。
Many interfaces consist of methods and no data members, so there is nothing to construct. 许多接口由方法组成,没有数据成员,因此无需构建。
class Field_Interface
{
public:
// Every field has a name.
virtual const std::string& get_field_name(void) const = 0;
// Every field must be able to return its value as a string
virtual std::string get_value_as_string(void) const = 0;
};
The above class is know as an abstract class. 上面的类被称为抽象类。 It is not meant to have any function, but to define an interface. 它不是要有任何功能,而是要定义一个接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.