简体   繁体   English

在C ++中初始化Class的成员变量的位置

[英]Where to initialize member variables of Class in C++

I just started using C++. 我刚开始使用C ++。 I have a question. 我有个问题。 Where should I initialize class member variables? 我应该在哪里初始化类成员变量? I have assigned some value to members variables using some member function. 我使用一些成员函数为成员变量赋予了一些值。 But static analysis tool is complaining about member initialization in constructor. 但静态分析工具抱怨构造函数中的成员初始化。 See following example: 请参阅以下示例:

test.cpp TEST.CPP

#include<iostream>
using namespace std;

class Point {
private:
    int x;
    int y;
public:
    Point(int r)
    {
      y = r;
    } 

    inline void setXval(int x_val) {
       x = x_val;
    }
};

Here, that tool says that x is not initialized in constructor. 这里,该工具表示x未在构造函数中初始化。 But I am setting x value in member function. 但我在成员函数中设置x值。 Is it correct way to do this or we should always initialize all members in default constructor? 这是正确的方法吗?或者我们应该始终初始化默认构造函数中的所有成员? Any help is much appreciated. 任何帮助深表感谢。 Thanks in advance ! 提前致谢 !

All variables should get an explicit value in the constructor. 所有变量都应该在构造函数中获得显式值。 You're not giving any value to x , so your tool is correct. 你没有给x任何价值,所以你的工具是正确的。 You might or might not call the member function that sets the value for x later - You cannot count that you (or a user of your code) will call that function before you need the value of x somewhere. 您可能会或可能不会调用稍后设置x的值的成员函数 - 您不能指望您(或代码的用户)在您需要某个x的值之前调用该函数。

Your tool want that you use initializer list: 您的工具希望您使用初始化列表:

class Point {
private:
    int x;
    int y;
public:
    Point(int x, int y) : x(x), y(y) {}
};

You should construct every class member in a constructor. 您应该在构造函数中构造每个类成员。 Member functions can change class members' values, but it can't construct them. 成员函数可以更改类成员的值,但不能构造它们。

Point(int _x, int _y): x(_x), y(_y) {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM