我看到了这个示例代码,它演示了对类的静态成员元素的访问。 然而,我注意到一个相同类名为“sum”的函数定义,我不明白,没有返回类型怎么能定义这样的东西。 这个函数“sum()”只增加一个计数值。 我对此有以下问题
下面是代码
#include <iostream>
using namespace std;
class test {
public:
static int count;
test() // Question : How does this work in c++. Is it like defining a function. If yes , there is no return type mentioned and yet the code works
{
count = ++count;
}
static void printcount(void)
{
cout << "count value :" << count << "\n";
}
};
int test::count;
int main()
{
test t1,t2;
test::printcount();
return 0;
}
此代码打印如下输出
计数值:2
有没有可能在一个类内定义一个函数,具有相同的类名而没有返回类型?
这样的函数将是一个称为构造函数的特殊成员函数。 在创建类类型的对象时调用构造函数。
构造函数只是在没有返回类型的情况下可以定义的函数。
这不违反函数定义的语法吗?
不。
是的。 这就是构造函数的语法。