提问者:小点点

这个简单的代码应该可以工作,但是我收到警告[重复]


#include <iostream>
using namespace std;

int *i = new int;
*i = 0;
int &j = *i;
j++;

//cout << *i << endl;

我有一个这样的代码,我知道这个语法是真的,但是它在Visual Studio代码中给出了如下警告:

quiz2_q8.cpp:5:4: error: expected constructor, destructor, or type conversion before '=' token
 *i = 0;
    ^
quiz2_q8.cpp:7:1: error: 'j' does not name a type
 j++;

我是否缺少一个要包含的库? 我以为iostream足够做这个测试代码了。


共3个答案

匿名用户

在全局命名空间中不能有任意的语句。 你需要把它放到一个函数中,例如:

int main() {
  int *i = new int;
  *i = 0;
  int &j = *i;
  j++;
}

匿名用户

要执行的语句必须在函数内部。

#include <iostream>
using namespace std;

int main(void) { // add this

    int *i = new int;
    *i = 0;
    int &j = *i;
    j++;

    //cout << *i << endl;

} // add this

匿名用户

大多数程序都有一个起点,那就是主要的方法/函数/过程不管你怎么称呼它。 每个函数都有一个由{//fun scope}给出的作用域。 一个很好的C++教程系列可能会对您有所帮助,或者一本书也可能会对您有所帮助。 这里有一个这样一个程序的模板。

#include <iostream>
using namespace std;

int main(){
   
    
   return 0;
}