首页 > 解决方案 > 如何重置传递给类构造函数的值?

问题描述

我有一个类向量。

    Vector::Vector(int x, int y, int z)
    {
        if (x > 100 || y > 100 || z > 100)
        {
            std::cout<<"the value should not be higher than 100"<<std::endl;
            this->x = 0; this->y = 0; this->z = 0; // This entry does not work
        }
    }

int main()
{
   Vector direction = Vector(100, 50, 10); // x has 100;
   std::cout << direction; // output 0, 0, 0
   return 0;
}

我该如何做到这一点,如果 3 个参数之一的值高于 100,那么它将被重置并且每个人都将拥有 0 0 0

标签: c++classconstructorconditional-statements

解决方案


首先,您没有重载的运算符要做cout<<direction;。此外,在您的构造函数中,您正在检查>100not>=100这就是为什么您没有得到输出

这是工作代码-

#include <iostream>
class Vector
{
    int x, y, z;

public:
    Vector(int, int, int);
    friend std::ostream &operator<<(std::ostream &, const Vector &);
};
std::ostream &operator<<(std::ostream &os, const Vector &obj)
{
    return os << obj.x << " " << obj.y << " " << obj.z;
}
Vector::Vector(int x, int y, int z)
{
    if (x >= 100 || y >= 100 || z >= 100)
    {
        std::cout << "the value should not be higher than 100" << std::endl;
        this->x = 0;
        this->y = 0;
        this->z = 0; // This entry does not work
    }
    else
    {
        this->x = x;
        this->y = y;
        this->z = z;
    }
}

int main()
{
    Vector direction = Vector(100, 50, 10); // x has 100;
    std::cout << direction;                 // output 0, 0, 0
    return 0;
}

推荐阅读