c++ - 需要帮助理解构造函数参数和静态变量

标签 c++ class oop static

这是一个简单的程序

#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/

相关文章:

c++ - static 是 C++ 中的修饰符吗?

c# - 如何将 List<T> 对象项目正确存储到 List<T> 的另一个实例而不影响其单个项目值 - C#

php - laravel 如何在静态方法中使用 $this 上下文?

ios - 在 ViewController 之前编译的自定义类

java - 涉及实现接口(interface)的实现问题

java - 如何解决 `Raw use of parameterized class ' Comparable'` 警告?

c++ - 异步写入套接字和用户值(boost::asio 问题)

c++ - 错误:无法将 std::vector<std::basic_string<char>> 转换为 std::string*

c++ - glBufferData 上的段错误

python - 覆盖字符串列表中属性的 getter 和 setter