不正确的输出和变量未在 Eclipse 的构造函数中初始化 CDT

Incorrect output and variables not initializing in constructor with Eclipse CDT

谁能给我解释一下为什么这段代码在 Eclipse 中不起作用 CDT?当我运行这个程序时,输出是“310598136”。我还在第 7 行收到一条错误消息,上面写着“‘成员 x(和 y)未在此构造函数中初始化”,但我不知道为什么当我在构造函数中有变量并在私有内存中分配内存时它们没有初始化class 的部分。有人可以告诉我我做错了什么吗?

#include <iostream>
using namespace std;

class Rectangle
{
public:
    Rectangle(int a, int b)
    {
        a = x;
        b = y;
    }
    int getArea();
private:
    int x;
    int y;
};

int Rectangle::getArea()
{
    return x * y;
}

int main()
{

    Rectangle bob(2,3);

    cout << bob.getArea();

    return 0;
}

您已经在构造函数中调换了变量的顺序。

改为

Rectangle(int a, int b) : x(a), y(b) {}

或者,更好

Rectangle(int x, int y) : x(x), y(y) {}

C++ 足够聪明,您可以在参数列表中使用与成员变量相同的名称,当您只是复制值时,您不妨这样做——它非常清楚地传达了该参数的含义是为了.

永远记住按照你在 class 中声明它们的顺序初始化你的成员变量。