Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C+;中,是否可以对所有内容使用一个构造函数+;? 我是C++初学者。我想创建一个简单的类来保存数字的总和。我是否必须在所有情况下使用4个不同的构造函数,或者我可以在一个类中实现所有可能性 class A { private: int total; int x, y, z; public: A() { total = 0; } A(int x) { this->x = x; total = x; } A(int x, int y) { total = x + y; this->x = x; this->y = y; } A(int x, int y, int z) { total = x + y + z; this->x = x; this->y = y; this->z = z; } }_C++_Class - Fatal编程技术网

在C+;中,是否可以对所有内容使用一个构造函数+;? 我是C++初学者。我想创建一个简单的类来保存数字的总和。我是否必须在所有情况下使用4个不同的构造函数,或者我可以在一个类中实现所有可能性 class A { private: int total; int x, y, z; public: A() { total = 0; } A(int x) { this->x = x; total = x; } A(int x, int y) { total = x + y; this->x = x; this->y = y; } A(int x, int y, int z) { total = x + y + z; this->x = x; this->y = y; this->z = z; } }

在C+;中,是否可以对所有内容使用一个构造函数+;? 我是C++初学者。我想创建一个简单的类来保存数字的总和。我是否必须在所有情况下使用4个不同的构造函数,或者我可以在一个类中实现所有可能性 class A { private: int total; int x, y, z; public: A() { total = 0; } A(int x) { this->x = x; total = x; } A(int x, int y) { total = x + y; this->x = x; this->y = y; } A(int x, int y, int z) { total = x + y + z; this->x = x; this->y = y; this->z = z; } },c++,class,C++,Class,我想你要找的是一个代表团。由于C++11,您可以从同一类的构造函数调用其他构造函数。这样可以避免编写重复的代码或额外的初始化方法 class A { private: int total = 0; int x = 0; int y = 0; int z = 0; public: A(int x) { this->x = x; this->total += x; } A(int x,

我想你要找的是一个代表团。由于C++11,您可以从同一类的构造函数调用其他构造函数。这样可以避免编写重复的代码或额外的初始化方法

class A
{
private:

    int total = 0;
    int x = 0;
    int y = 0;
    int z = 0;

public:

    A(int x)
    {
        this->x = x;
        this->total += x;
    }
    A(int x, int y) : A(x)
    {           
        this->y = y;
        this->total += y;
    }
    A(int x, int y, int z) : A(x, y)
    {
        this->z = z;
        this->total += z;           
    }
};
但是,对于您的特定示例,最好只使用默认参数,而不是使用多个构造函数:

class B
{
private:

    int total = 0;
    int x = 0;
    int y = 0;
    int z = 0;

public:

    B(int x = 0, int y = 0, int z = 0) : x(x), y(y), z(z)
    {
        this->total = x + y + z;
    }
};

阅读有关的内容。
A(intx=0,inty=0,intz=0){total=x+y+z;this->x=x;this->y=y;this->z=z;}
满足您的要求吗?(它将初始化未显式指定的变量,而原始代码不会)您所做的不好,因为某些成员可能未初始化。这里正确的方法是在构造函数中未传递时将y和z默认初始化为0。顺便说一句,如果您使用所有三个构造函数,它们都需要初始化所有成员变量。如果没有,在这里的例子中,一些
int
成员可能未初始化,访问它们的值会给出未定义的行为。或者。在你写的声明中,
intx=0,y=0,z=0