简体   繁体   English

用户定义的c ++常量变量

[英]c++ constant variable defined by user

My program uses number PI. 我的程序使用数字PI。 It should be constant value const double PI = 3.14 . 它应该是常数const double PI = 3.14 I want that user of the program could define this constants during Initialization of the class. 我希望程序的用户可以在类初始化期间定义此常量。 For example, one of them want 3.14 and another 3.1416926. 例如,其中一个要3.14,另一个要3.1416926。 And after definition it should be constant value, ie during program nobody can change it. 并且在定义之后,它应该是恒定值,即在程序执行过程中没有人可以更改它。 How can I implement it? 我该如何实施?

You can create a per- instance constant using a constant member: 您可以使用常量成员创建每个实例的常量:

class MyClass {
    MyClass(double pi): PI(pi) { ... }
    const double PI;
};

Each object creator my specify a value of PI to use, which is constant for the lifetime of that object: 每个对象创建者都可以指定要使用的PI值,该值在该对象的生存期内是恒定的:

MyClass obj1(3.14);
MyClass obj2(3.1416926);

Put const double PI = 3.141592653589793238462643383279502884197169399375105820974944 in a .h header file and include it in the .cpp file. const double PI = 3.141592653589793238462643383279502884197169399375105820974944放在.h头文件中,并将其包括在.cpp文件中。 Or you will get that error. 否则您将得到该错误。

pi.h h

const double PI = 3.141592653589793238462643383279502884197169399375105820974944;

Pi.cpp c

#include <iostream>
#include "pi.h"
using namespace std;

class  Pi_Class
{
        public:

        double m_PI;

        Pi_Class()
        {
                     cout<<PI<<" \n";
        }

        Pi_Class(double fPI )
        {
            m_PI=fPI; 
                    cout<<m_PI<<" \n";
        }
};


int main()
{

   Pi_Class Pi_one(3.141);
   Pi_Class Pi_two(3.1415926535);
   Pi_Class Pi_thr(3.141592653589793238462643383279502884197169399375105820974944 );

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM