[英]C++ access constant value declared in cpp
I have a main method in my main.cpp
that I would like to display the value of a constant int
I have declared. 我的
main.cpp
中有一个main方法,我想显示我声明的常量int
的值。
I added a DeclareConstant
class. 我添加了一个
DeclareConstant
类。
Here is my DelcareConstant.h 这是我的DelcareConstant.h
#pragma once
class DeclareConstant
{
public:
const int x;
Part1(void);
Part1(int x);
~Part1(void);
double getX(){return x;}
};
And source 和来源
#include "Part1.h"
Part1::Part1() : x(55){
}
How can I access X so I can display it in my main method? 如何访问X,以便可以在主要方法中显示它? I need to check if I'm even initializing it correctly.
我需要检查我是否正确初始化了它。
You can access x
through getter function getX()
, for example: 您可以通过getter函数
getX()
访问x
,例如:
DeclareConstant dc;
std::cout << dc.getX() << std::endl;
Or 要么
DeclareConstant dc;
std::cout << dc.x << std::endl;
However, you should define your getX like this: 但是,您应该这样定义getX:
class DeclareConstant
{
public:
int getX() const {return x;}
private:
const int x;
};
And please hide your class member. 并且请隐藏您的班级成员。
You need an object or an instance of DeclareConstant
to access the DeclareConstant
's x
member. 您需要一个
DeclareConstant
对象或实例才能访问DeclareConstant
的x
成员。
DeclareConstant myConst;
std::cout << myConst.x << std::endl; // Use x
But for your possible purpose and intentions you could make x
as a static member . 但是出于您可能的目的和意图,您可以将
x
设为静态成员 。
class DeclareConstant {
public:
static const int x = 55;
// ...
}
You now don't need an instance to get the value of x
: 您现在不需要实例来获取
x
的值:
std::cout << DeclareConstant::x << std::endl; // Use x
If all your instances use the same constant value, you can make it static. 如果所有实例都使用相同的常量值,则可以将其设为静态。 This has a couple of advantages.
这有两个优点。
You can define it as below. 您可以如下定义。
class Part1{ 第1部分类{
public: static const int x = 42; public:静态const int x = 42; Part1(void);
Part1(void); Part1(int x);
Part1(int x); ~Part1(void);
〜Part1(无效); double getX(){return x;} };
double getX(){return x;}};
and access it simply as Part1::x
. 并以
Part1::x
身份进行访问。 You should make getX
static as well, then you can do Part1::getX()
. 您还应该使
getX
静态,然后可以执行Part1::getX()
。
This will not work if each instance has its own const
value. 如果每个实例都有自己的
const
值,则此方法将无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.