mercredi 23 avril 2014

C++ - Confusion over particular example of class instantiation from Professor


Vote count:

0




My professor gave the following code:



#include "state.h"
#include <string>
#include <iostream>

using namespace std;

int main(int argc, char const *argv[]){

const int success = 0;
string name;

State x;

State y = "s2"; // This doesn't compile
State z = y;
State* p = new State(z);

x = *p;
p->set_name("s3");
delete p;
x.get_name(name);

std::cout << "Name of state x is " << name << std::endl;
std::cout << "Total number of states is " << State::total_number_of_states() << std::endl;

return success;
}


In g++ 4.8 on Ubuntu, I get the following error:



$ g++ example_main_1.cpp state.cpp
example_main_1.cpp: In function ‘int main(int, const char**)’:
example_main_1.cpp:14:12: error: conversion from ‘const char [3]’ to non-scalar type ‘State’ requested
State y = "s2"; // This doesn't compile


I asked him about this in class, he said that this is valid C++ and that it should work. I've never seen this kind of class instantiation before, where it would have to convert from a string literal to a std::string then convert that to a State object.


My professor then went on to point out that there are other equivalent invocations that are extremely close:



State y = "s2"; // Does NOT compile
State y("s2"); // Does compile
State y = string("s2"); // Does compile


What's going on here? Why does the first not compile, but the second and third do? As well, is my professor mistaken in saying that the first statement should work? Or is it behavior that's compiler specific?



asked 5 mins ago


1 Answer



Vote count:

1




It looks like your State object has a constructor that takes string. The literal "s2" is type const char*. This is why you are receiving the error.



answered 1 min ago

awesomeyi

2,990




Aucun commentaire:

Enregistrer un commentaire