这是一个简单的程序
#include <iostream>
using namespace std;
class Employee
{
public:
Employee(string="default", int=10){};
void display();
private:
static int x;
static string s;
};
int Employee::x=7;
string Employee::s="Johnson";
void Employee::display()
{
cout << s << x << endl;
}
int main()
{
int num;
string name;
Employee e1;
Employee e2("Arthur",33);
e2.Employee::display();
}
我有以下问题
1) 我需要帮助来理解为什么程序的输出是 Johnson7
而不是 Arthur33
(我知道它与静态变量有关)
2) 通常构造函数是这样定义的 Employee(string,int)
构造函数中的参数string="default",int=10有什么作用
Employee(string="default", int=10){};
实际上是指???
最佳答案
1) I need help understanding why the output of the program is Johnson7 and not Arthur33( i know it has something to do with static variables )
因为 display()
打印静态数据成员。构造函数根本不会影响它。事实上,它对其参数没有任何作用。
2) Normally a constructor is defined as such Employee(string,int). What does the parameters string="default",int=10 in the constructor
这些是默认参数。这意味着如果您不提供部分或全部参数,则会采用默认值。例如:
void foo(int i = 42, double d = 3.1416);
foo(1, 2.3); // calls with i = 1, d = 2.3
foo(1); // calls with i = 1, d = 3.1416
foo(); // calls with i = 42, d = 3.1416
这对您的示例没有影响,因为您的构造函数无论如何都不会对参数执行任何操作。
这些东西在最基本的 C++ 书籍中都有解释。看看the definitive list .
关于c++ - 需要帮助理解构造函数参数和静态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20303293/