【问题标题】:I can't access to the attribute of my class with C++我无法使用 C++ 访问我的类的属性
【发布时间】:2015-04-02 23:37:36
【问题描述】:

我在使用 C++ 时遇到问题,无法访问我的类的属性Temperatura

这是我项目的结构: my project structure

文件Temperatura.h代码:

#ifndef TEMPERATURA_H_
#define TEMPERATURA_H_

 class Temperatura
{
private:
    float temperatura;

public:
    Temperatura(float);

    //SET's
    void setKelvin(float);
    void setCelsius(float);
    void setFahrenheit(float);

    //GET's
    float getKelvin();
    float getCelsius();
    float getFahrenheit();
};
#endif

文件Temperature.cpp代码:

#include "headers/Temperatura.h"
#include <iostream>

using namespace std;

Temperatura::Temperatura(float t)
{
    temperatura = t;
}

//SET's
void Temperatura::setKelvin(float t)
{
    temperatura = t;
    return;
}

void Temperatura::setCelsius(float t)
{
    temperatura = t + 273.15;
    return;
}

void Temperatura::setFahrenheit(float t)
{
    temperatura = ((t-32)/1.8)+273.15;
    return;
}

//GET's
float getKelvin()
{
    float t = temperatura;
    return t;
}

float getFahrenheit()
{
    return ((9*temperatura)/5)-459.67;
}

float getCelsius()
{
    return temperatura-273.15;
}

以及文件Programa1.cpp代码:

#include "headers/Temperatura.h"
#include <iostream>

using namespace std;

int main(int argc, char const *argv[])
{
    Temperatura t(0);
    float grados;

    cout << "Introduzca los grados el setKelvin: ";
    cin >> grados;

    t.setKelvin(grados);
    grados = t.getCelsius();

    cout << "Grados en Celsius: " << grados << endl;

    return 0;
}

输出控制台是:

hunter@Hunter-Elementary:~/Documentos/Distribuidos/Clases/Clase 
2/Proyecto1/Programa1$ g++ *.cpp -o Programa1
Temperatura.cpp: En la función ‘float getKelvin()’:
Temperatura.cpp:33:12: error: ‘temperatura’ no se declaró en este ámbito
Temperatura.cpp: En la función ‘float getFahrenheit()’:
Temperatura.cpp:39:13: error: ‘temperatura’ no se declaró en este ámbito
Temperatura.cpp: En la función ‘float getCelsius()’:
Temperatura.cpp:44:9: error: ‘temperatura’ no se declaró en este ámbito

对不起我的英语,我说西班牙语:/

【问题讨论】:

    标签: c++ function class attributes


    【解决方案1】:

    您需要像使用 setter 函数一样确定 getter 函数的范围。

    float Temperatura::getKelvin()
    {
        float t = temperatura;
        return t;
    }
    

    这意味着该函数是Temperatura类的方法

    【讨论】:

    • 非常感谢您。我有点瞎,没有注意到。 :)
    猜你喜欢
    • 2019-10-21
    • 2012-06-19
    • 2016-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 2014-12-09
    相关资源
    最近更新 更多