具有float变量的类

时间:2016-02-27 18:15:36

标签: c++

我在这里有一个带变量的简单类。为什么它不返回变量10.5的值?

输出

Test! -1.09356e+09

#include "iostream"

using namespace std;

class Txtbin{
    protected:
        float area;

    public:
        Txtbin();
        float get_area();
};

Txtbin::Txtbin(){
    float area = 10.5;
}

float Txtbin::get_area(){
    return area;
}

int main(int argc, char* argv[]){
    Txtbin a;
    cout << "Test! " << a.get_area() << endl;

    return 0;
}

2 个答案:

答案 0 :(得分:5)

这是创建一个局部变量,而不是初始化你的成员:

Txtbin::Txtbin(){
    float area = 10.5; // creates a variable called area that isn't used.
}

您应该像这样初始化您的成员

Txtbin::Txtbin()
: area(10.5)
{
}

如果您使用的是C ++ 11或更新版本,或者可能直接在课堂上使用:

class Txtbin{
    protected:
        float area = 10.5;

    public:
        Txtbin();
        float get_area();
};

答案 1 :(得分:0)

此处新的area声明会影响该成员。

Txtbin::Txtbin(){
    float area = 10.5;
}

如果启用更多/所有警告,编译器可能会告诉您更多。

e.g。

$ clang++ -Weverything tmp/foo.cpp
tmp/foo.cpp:16:11: warning: declaration shadows a field of 'Txtbin' [-Wshadow]
    float area = 10.5;
          ^
tmp/foo.cpp:8:15: note: previous declaration is here
        float area;
              ^
tmp/foo.cpp:16:11: warning: unused variable 'area' [-Wunused-variable]
    float area = 10.5;
          ^
tmp/foo.cpp:23:14: warning: unused parameter 'argc' [-Wunused-parameter]
int main(int argc, char* argv[]){
             ^
tmp/foo.cpp:23:26: warning: unused parameter 'argv' [-Wunused-parameter]
int main(int argc, char* argv[]){
                         ^
4 warnings generated.

相反,请在构造函数中使用成员初始值设定项。

class Txtbin{
    protected:
        float area;

    public:
        Txtbin();
        float get_area();
};

Txtbin::Txtbin()
   : area(10.5) {
}