C++ 获取并设置函数c++;
我只是想知道是否有人能帮我修改代码,我有点困惑为什么它不能像我希望的那样工作,也许我误解了什么…程序的要点是编写一个包含两个函数的类来设置和获取一个数字,但稍后在代码的主要部分,我希望它打印出一个2.52的数字,而不仅仅是数字2。如果有人帮助,谢谢:)C++ 获取并设置函数c++;,c++,function,class,visual-c++,methods,C++,Function,Class,Visual C++,Methods,我只是想知道是否有人能帮我修改代码,我有点困惑为什么它不能像我希望的那样工作,也许我误解了什么…程序的要点是编写一个包含两个函数的类来设置和获取一个数字,但稍后在代码的主要部分,我希望它打印出一个2.52的数字,而不仅仅是数字2。如果有人帮助,谢谢:) #包括 #包括 使用名称空间std; 班级 { 公众: 无效集(浮动x) { 数字=x; } int Get() { 返回号码; } 私人: 浮点数; }; int main() { 类对象; 对象集(2.52); cout您可以这样更改get方
#包括
#包括
使用名称空间std;
班级
{
公众:
无效集(浮动x)
{
数字=x;
}
int Get()
{
返回号码;
}
私人:
浮点数;
};
int main()
{
类对象;
对象集(2.52);
cout您可以这样更改get方法类型(float)
class Class
{
public:
void Set(float x)
{
number = x;
}
float Get()
{
return number;
}
private:
float number;
};
int main()
{
Class object;
object.Set(2.52);
cout << "The number is: " << object.Get();
return 0;
}
类
{
公众:
无效集(浮动x)
{
数字=x;
}
float Get()
{
返回号码;
}
私人:
浮点数;
};
int main()
{
类对象;
对象集(2.52);
cout首先,从Get()
返回int
,因此number
将在int
中转换
您还应该使Get()
const
,因为它在调用函数时不会改变类
对象中的任何内容。使它成为常量
可以通过const&
将类
的实例传递给使用类的函数:
#include <iostream>
class Class
{
public:
void Set(float x)
{
number = x;
}
float Get() const // returning float and added const
{
return number;
}
private:
float number;
};
void tester(const Class& obj) // a function taking a Class by const reference:
{
std::cout << "The number is: " << obj.Get() << '\n';
}
int main()
{
Class object;
object.Set(2.52);
tester(object);
}
#包括
班级
{
公众:
无效集(浮动x)
{
数字=x;
}
float Get()const//返回float和added const
{
返回号码;
}
私人:
浮点数;
};
void tester(const Class&obj)//一个函数通过const引用获取一个类:
{
std::可能您想将int Get()
更改为float Get()
;)?Get返回一个int。当执行object.Get()
时,您设置的number
的值2,53将转换为int
:2。这是输出的内容。@user12577611请阅读
#include <iostream>
class Class
{
public:
void Set(float x)
{
number = x;
}
float Get() const // returning float and added const
{
return number;
}
private:
float number;
};
void tester(const Class& obj) // a function taking a Class by const reference:
{
std::cout << "The number is: " << obj.Get() << '\n';
}
int main()
{
Class object;
object.Set(2.52);
tester(object);
}