c++ - 如何重置传递给类构造函数的值?
问题描述
我有一个类向量。
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
解决方案
首先,您没有重载的运算符要做cout<<direction
;。此外,在您的构造函数中,您正在检查>100
not>=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;
}
推荐阅读
- angular - Argument type string | null is not assignable to parameter
- django - .gitignore 上要忽略的 Docker 文件
- sql-server - App_name 为 system.data.sqlclient
- javascript - JavaScript 中单选/复选框按钮的实时验证
- mysql - MySQL 与先前值的增量
- ruby-on-rails - ArgumentError(错误数量的参数(给定 1,预期 2))
- reactjs - 来自 localStorage 的令牌未定义
- r - 序数逻辑回归 - 整数因变量显示每个数据点的相关性
- php - 方法 Illuminate\Support\Collection::links 不存在。(查看:C:\xampp\htdocs\ContentBaseApp\resources\views\projects\index.blade.php)
- java - 我的 Java 项目没有打印出任何东西