C++ 是否可以使用类实例名获取私有变量值?
例如,我编写了一个名为C++ 是否可以使用类实例名获取私有变量值?,c++,C++,例如,我编写了一个名为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
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;
}
类长度{
公众:
无效设置值(浮动);
私人:
浮点数;
};
无效的
长度::设置值(浮动新值){
值=新值;
}
无效打印(浮动值){
std::cout您需要定义一个操作符()
方法来打印值5。您需要定义一个操作符()
方法来打印值5。您需要定义一个操作符()
方法来打印值5。您需要定义一个操作符()
方法打印值5。从技术上讲,width
不是实例名称,而是Length
类型变量的名称。您可以通过两种方式更改代码以检索变量:
- 添加一个
friend
操作符从技术上讲,width
不是实例名,而是Length
类型变量的名称。您可以通过两种方式更改代码以检索变量:
- 添加一个
friend
操作符从技术上讲,width
不是实例名,而是Length
类型变量的名称。您可以通过两种方式更改代码以检索变量:
- 添加一个
friend
操作符从技术上讲,width
不是实例名,而是Length
类型变量的名称。您可以通过两种方式更改代码以检索变量:
- 添加一个
朋友操作符你必须重载操作符你必须重载操作符你必须重载操作符你必须重载操作符你需要重载你需要重载你需要重载你需要重载你背后的理由是什么“在std名称空间中使用重载时,我建议小心。在std名称空间中使用重载时,我建议小心的理由是什么。在std名称空间中使用重载时,我建议小心的理由是什么。你的理由是什么?”重载我建议在std名称空间中使用时要小心。@DleanJeansconst Length&
和operator float()const
确保运算符可以应用于Length
对象,即使它们声明为const Length myLength
@DleanJeansconst Length&
和operator float()const
确保运算符可以应用于Length
对象,即使它们被声明为const Length myLength
@DleanJeansconst Length&
和运算符float()const
确保运算符可以应用于Length
对象,即使它们被声明为const Length myLength
@DleanJeansconst Length&
和运算符float()const
确保运算符可以应用于Length
对象,即使它们被声明为const Length myLength
。
friend ostream& operator <<(ostream& out, const Length& len) {
out << len.value_;
return out;
}
class Length {
...
public:
operator float() const { return value_; }
};
class Length
{
..
friend std::ostream& operator<<(std::ostream& os, const Length& o);
..
}
std::ostream& operator<<(std::ostream& os, const Length& o)
{
os << o.value_;
return os;
}
#include <iostream>
class Length {
friend std::ostream& operator<<(std::ostream& os, const Length& l);
public:
void setValue(float);
private:
float value_;
};
void
Length::setValue(float newValue) {
value_ = newValue;
}
std::ostream& operator<<(std::ostream& os, const Length& l)
{
os << l.value_;
return os;
}
int main() {
Length width;
width.setValue(5);
std::cout << width << std::endl; // print 5
return 0;
}
#include <iostream>
class Length {
friend std::ostream& print(std::ostream &,const Length &l);
public:
void setValue(float);
private:
float value_;
};
void
Length::setValue(float newValue) {
value_ = newValue;
}
std::ostream& print(std::ostream &os, const Length &l)
{
os << l.value_;
return os;
}
int main() {
Length width;
width.setValue(5);
print(std::cout, width) << std::endl;
return 0;
}