C++代码出现问题求各位解答


#include <iostream>
using namespace std;
 
class test
{
        const double pi;
    public:
        test(): pi(3.14) { }
        void show()
        {
            cout << "The low-precision pi is " << pi << endl;
            pi = 3.14159;
            cout << "The high-precision pi is " << pi << endl;
        }
};
 
int main()
{
    test A;
    A.show();
}

预期结果:
The low-precision pi is 3.14
The high-precision pi is 3.14159

const double pi;
这是常量,不能修改,去掉 const

 
#include <iostream>
using namespace std;
 
class test
{
        double pi;
    public:
        test(): pi(3.14) { }
        void show()
        {
            cout << "The low-precision pi is " << pi << endl;
            pi = 3.14159;
            cout << "The high-precision pi is " << pi << endl;
        }
};
 
int main()
{
    test A;
    A.show();
}

img

  • 这有个类似的问题, 你可以参考下: https://ask.csdn.net/questions/7553099
  • 这篇博客也不错, 你可以看下C++代码实现获取系统时间精确到毫秒级
  • 除此之外, 这篇博客: C++ 形参初始化及析构顺序中的 测试代码: 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • #include <iostream>
    using namespace std;
    class Test
    {
    public:
    	Test(int);
    	Test(Test&);
    	~Test();
    
    private:
    	int a;
    };
    
    Test::Test(int i)
    {
    	a = i;
    	cout << "constructing  " << a << endl;
    }
    Test::Test(Test& test)
    {
    	a = test.a;
    	cout << "copying   " << a << endl;
    }
    
    Test::~Test()
    {
    	cout << "destructing   " << a << endl;
    }
    
    void outPut(Test test1, Test test2);
    
    int main() {
    	Test* a = new Test(3);
    	Test test1(1);
    	Test test2(2);
    	outPut(test1, test2);
    	system("pause");
    	return 0;
    }
    void outPut(Test test1, Test test2) {
    }
    
  • 您还可以看一下 李云生老师的C++程序员内功修炼之道课程中的 互联网与数字化小节, 巩固相关知识点