dimanche 29 mai 2016

how to initialize a string pointer as a class member in C++?

I using G++ 5.2.0 on a Windows 10 64bit machine. And I have the following code as string_toy.cpp

#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
class MyClass{
private:
    std::string * name;
    int * type;
public:
    void setNameNType(int);
    std::string getName();
    void getType();

    MyClass(int n){
        setNameNType(n);
    }

    ~MyClass(){
        delete type;
        delete name;
        cout << "Destructor Called" << endl;
    }
};

void MyClass::setNameNType(int n){
    type = new int;
    *type = n;
    if (n == 0) name = new std::string("A");
    if (n == 1) name = new std::string("B");
}

std::string MyClass::getName(){
    return *name;
}

int main(void){
    MyClass p(0);
    cout << p.getName() << endl;
    getchar();
    return 0;
}

When I am using g++ to compile with the commandg++ string_toy.cpp -Werror, it complied the code without any error showing. However, when I run the output a.exe file with command ./a, it outputs nothing. And when I double click the a.exe file, it pops out the following window:Entry Point Not Found Also, I put the code in Visual Studio 2013 and it successfully compiles it and the output is perfect.

I was wondering if I'm doing anything wrong with the G++?

Thank you!

Aucun commentaire:

Enregistrer un commentaire