是否可以使用类实例名获取私有变量值? [英] Is it possible to get private variable value using class instance name?

查看:130
本文介绍了是否可以使用类实例名获取私有变量值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我写了一个类 Length

class Length {
public:
    void setValue(float);
private:
    float value_;
};

void
Length::setValue(float newValue) {
    value_ =  newValue;
}
void print(float value) {
    std::cout << value;
}

void computeStuff(float value) {
    //do the computing
}

int main() {

    Length width;
    width.setValue(5);
    std::cout << width; // <-- this is actually just an example
    //what I actually want is:
    print(width); // print 5
    //or perhaps even
    computeStuff(width);

    return 0;
}

现在如何使 width return value _ 5

Now how to make width return value_ or 5?

推荐答案

技术上, width 不是实例名称,它是长度。您可以通过以下两种方式更改代码以检索变量:

Technically, width is not an instance name, it's a name of a variable of type Length. You can change your code to retrieve a variable in two ways:


  • 添加朋友 c>
  • >从长度 float 添加隐式转换运算符。
  • Add a friend operator << for Length that does the printing, or
  • Add an implicit conversion operator from Length to float.

第一种方法仅适用于输出。您不能直接拉取值:

The first approach works only for output. You cannot pull the value directly:

friend ostream& operator <<(ostream& out, const Length& len) {
    out << len.value_;
    return out;
}

第二种方法如下:

class Length {
    ...
public:
    operator float() const { return value_; }
};

这篇关于是否可以使用类实例名获取私有变量值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆