getter函数是如何返回错误值的?
我为 C++ 定义了三个文件来实现一个类:
颜色.hpp
#ifndef COLOR_HPP
#define COLOR_HPP
class Color {
public:
void rset(int rr); // mutator, mutates r_
void gset(int gg);
void bset(int bb);
int rget() const; // accessor, object.r() gets the r channel
int bget() const;
int gget() const;
private:
bool ValidColorValue(int value) const;
int r_;
int b_;
int g_;
static constexpr int kMaxColorValue = 255;
static constexpr int kMinColorValue = 0;
};
#endif
颜色.cpp
// put by convention, defines methods in color.hpp
#include <stdexcept>
#include "color.hpp"
void Color::rset(int rr) {
if (ValidColorValue(rr)) {
r_ == rr;
} else {
throw std::runtime_error("Invalid Red channel value");
}
}
void Color::bset(int bb) {
if (ValidColorValue(bb)) {
b_ == bb;
} else {
throw std::runtime_error("Invalid Blue channel value");
}
}
void Color::gset(int gg) {
if (ValidColorValue(gg)) {
g_ == gg;
} else {
throw std::runtime_error("Invalid Green channel value");
}
}
int Color::rget() const { return r_; }
int Color::bget() const { return b_; }
int Color::gget() const { return g_; }
bool Color::ValidColorValue(int value) const {
if (value >= kMinColorValue && value <= kMaxColorValue) {
return true;
} else {
return false;
}
}
主程序
#include <string>
#include <iostream>
#include "color.hpp"
int main() {
Color c;
c.rset(32);
std::cout << c.rget() << std::endl;
c.rset(11);
std::cout << c.rget() << std::endl;
}
我g++ color.cpp main.cpp在输入命令之前用命令编译./a.out,我在命令行中得到了这个结果:
奇怪的是,当我./a.out再次输入时,我得到两个不同的数字:
到底是怎么回事?如何使用 32 然后 11 作为输出获得预期的行为?
回答
您既不初始化也不分配成员,因此每个值都是不确定的。你的 getter 读取不确定的值,所以程序的行为是未定义的。
我如何获得预期的行为
您正在使用==相等运算符。改用=赋值运算符,例如:
r_ = rr;