[英]accessing a static variable in C++
我正在使用Qt Creator嘗試創建一個基本的計算器應用程序。 我試圖測試前幾個方法,並且必須編寫一個以便使編碼的其余部分更容易,但是,該方法沒有編譯。 我正在嘗試訪問一個保存Calculator屏幕當前值的靜態變量,但它一直給我:
C:\Users\****\Documents\Qt Projects\SimpleCalculator\calculator.cpp:15: error: C2248: 'Calculator::currVal' : cannot access private member declared in class 'Calculator'
這是Calculator.cpp
#include "calculator.h"
#include <QLCDNumber>
Calculator::Calculator(QWidget *parent) :
QWidget(parent), ui(new Ui::Calculator)
{
ans = 0;
currVal = 0;
setupUi(this);
}
//problem method
QString getNewVal(qint64 nextDig)
{
//--------------------------------------------
long long int val = Calculator::currVal;//this is where I am trying to access the variable
//--------------------------------------------
if(nextDig==0)
{
if(val > 0)
{
QString str = QString::number(val);
str.append("0");
return str;
}
else
{
return "0";
}
}
else if(nextDig==1)
{
QString str = QString::number(val);
str.append("1");
return str;
}
return NULL;
}
void Calculator::on_Zero_clicked()
{
ui->Display->display(getNewVal(0));
currVal = ui->Display->intValue();
}
void Calculator::on_One_clicked()
{
}
這是頭文件:
#ifndef CALCULATOR_H
#define CALCULATOR_H
#include "ui_calculator.h"
class Calculator : public QWidget, private Ui::Calculator
{
Q_OBJECT
public:
Calculator(QWidget *parent = 0);
private slots:
void on_Zero_clicked();
void on_One_clicked();
private:
Ui::Calculator *ui;
QString getNewVal(quint64);
static long long int ans;
static long long int currVal;
};
long long int Calculator::ans = 0;
long long int Calculator::currVal = 0;
#endif
// CALCULATOR_H
Calculator::currVal;//this is where I am trying to access the variable
無效,因為標頭中的值被聲明為私有(如警告所示):
private:
Ui::Calculator *ui;
QString getNewVal(quint64);
static long long int ans;
**static long long int currVal;**
和你的功能:
QString getNewVal(qint64 nextDig)
不屬於班級。
這個
static long long int currVal;
是私人的!
嘗試:
public:
static long long int currVal;
或為此創建一個getter方法。
你也可以讓getNewVal
成為你班級的朋友功能:
public:
friend QString ::getNewVal(qint64 nextDig);
您需要指定getNewVal
屬於Calculator
QString Calculator::getNewVal(quint64 nextDig)
// ^^^^^^^^^^ ^
// This was missing |
// |
// Add 'u' above to match the declaration
否則,C ++認為這是一個獨立的函數(盡管你在Calculator
聲明了一個具有相同名稱的成員函數)。
您還需要移動這兩個定義
long long int Calculator::ans = 0;
long long int Calculator::currVal = 0;
從頭文件到實現文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.