Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/154.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 获取并设置函数c++;_C++_Function_Class_Visual C++_Methods - Fatal编程技术网

C++ 获取并设置函数c++;

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方

我只是想知道是否有人能帮我修改代码,我有点困惑为什么它不能像我希望的那样工作,也许我误解了什么…程序的要点是编写一个包含两个函数的类来设置和获取一个数字,但稍后在代码的主要部分,我希望它打印出一个2.52的数字,而不仅仅是数字2。如果有人帮助,谢谢:)

#包括
#包括
使用名称空间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);
}