例如,我写了一个名为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
返回value_
或5
?
答案 0 :(得分:2)
从技术上讲,width
不是实例名称,而是Length
类型变量的名称。您可以通过两种方式更改代码以检索变量:
friend
添加<<
运算符Length
,或Length
添加隐式转换运算符到float
。第一种方法仅适用于输出。你无法直接提取价值:
friend ostream& operator <<(ostream& out, const Length& len) {
out << len.value_;
return out;
}
第二种方法如下:
class Length {
...
public:
operator float() const { return value_; }
};
答案 1 :(得分:1)
您必须为自定义类型重载operator<<
,例如:
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;
}
请注意这个
<iostream>
答案 2 :(得分:0)
您需要定义operator()
方法来打印值5。
答案 3 :(得分:0)
您需要为您的班级重载<<
运算符。您还可以使用函数来完成操作员的工作。
运营商<<
#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;
}