【问题标题】:Assign value to dynamically allocated integer为动态分配的整数赋值
【发布时间】:2020-03-19 06:45:17
【问题描述】:

更新:
感谢大家帮助理解这一点!

我尝试运行这个:

#include <iostream>

int* x = new int;
*x = 5;

int main()
{

}


我收到以下错误:

1>------ Build started: Project: learnCpp, Configuration: Debug Win32 ------
1>learnCpp.cpp
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(4,6): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(4,2): error C2374: 'x': redefinition; multiple initialization
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(3): message : see declaration of 'x'
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(4,7): error C2440: 'initializing': cannot convert from 'int' to 'int *'
1>C:\Users\Danie\source\repos\learnCpp\learnCpp.cpp(4,4): message : Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
1>Done building project "learnCpp.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========


但是,如果我在主函数中将值分配给 x,我不会收到任何错误。
像这样:

#include <iostream>

int* x = new int;


int main()
{
    *x = 5;
}

怎么会?

【问题讨论】:

标签: c++ c scope namespaces declaration


【解决方案1】:

在 C 语言的文件范围内,您只能放置声明。您不能在文件范围内执行语句。这同样适用于 C++,您可以将声明放在仅命名空间中。

注意:在 C 中声明不是语句,而在 C++ 中声明是语句。然而,除了声明语句之外,其他语句可能不会出现在 C++ 的命名空间中。还值得注意的是,在 C 中有一个 null 语句,但没有一个空声明。而在 C++ 中可能有一个空声明。

所以这个程序

#include <iostream>

int* x = new int;
*x = 5;

int main()
{

}

无效。

编译器的这些错误信息

error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2374: 'x': redefinition; multiple initialization
message : see declaration of 'x'

表示编译器试图将赋值语句解释为声明。

但是这个程序

#include <iostream>

int* x = new int;

int main()
{
    *x = 5;
}

是正确的。在这个程序中,赋值语句存在于函数 main 的外部块范围内。

【讨论】:

    【解决方案2】:

    您尝试做的事情在全球范围内是不可能的。

    如果您需要这样做,请尝试如下初始化:

    // good practice 
    namespace
    {
        int* x = new int(5);
    }
    
    int main()
    {
        // You can later modify in function scope
        *x = 10;
    }
    

    【讨论】:

      【解决方案3】:

      除了声明之外,您不能有任何范围之外的语句(为简单起见,请考虑括号内的范围)。所以,编译器试图解释

      *x = 5;
      

      作为声明,作为给定类型的指针,但是找不到指向的类型,所以会产生错误。

      【讨论】:

        猜你喜欢
        • 2019-04-22
        • 1970-01-01
        • 1970-01-01
        • 2010-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多