简体   繁体   中英

Microsoft Visual C++ 2010 Express - error in correct code

I copied&pasted code from The Programming Language 4th Edition 2013 :

编程语言2013年第4版,第49页

to Microsoft Visual C++ 2010 Express and compiled. I got many errors, why? The version of compilator is old? I didn't have all code to run it? Microsoft Visual C ++ 2010 Express

Copying code:

#include <iostream>
#include <cstdio>
using namespace std;


class vector{
public:
    vector(int s) :elem{new double[s]}, sz{s} {}
    double& operator[](int i) {return elem[i];}
    int size() {return sz;}
private:
    double* elem;
    int sz;
};


void main()
{
    vector v(6);
}

[EDIT]When I use Visual Studio 2013:

Visual Studio 2013

As commented above, your syntax uses C++11, which is not available in Visual Studio 2010.

However, small changes in the code will make it compile. Just replace {} by () in constructor line + make main() return something (dunno if that's specific to C++11, but my compiler did not want to compile with a void main).

#include <iostream>
#include <cstdio>
//using namespace std; commented, it's useless and confusing


class vector{
public:
    vector(int s) : elem(new double[s]), sz(s) {}
    double& operator[](int i) {return elem[i];}
    int size() {return sz;}
private:
    double* elem;
    int sz;
};


int main()
{
    vector v(6);
    return 0;
}

The same code works in VS2013. You are using C++ 11 specific code and probably the cl on your VS2010 does not know C++11.

This line is C++ 11 like:

vector(int s) :elem{new double[s]}, sz{s} {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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