我的教授给出了以下代码:
#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;
}
#ifndef STATE_H
#define STATE_H
#include <string>
using namespace std;
class State
{
private:
string* name; // str pointer used for illustrative purposes
static int number_of_states;
public:
State();
State(string state_name);
State(const State& state); // Will basically be the copy constructor
virtual ~State();
State& operator=(const State& state); // Copy on equal
void get_name(string& state_name) const;
void set_name(string state_name);
static int total_number_of_states();
};
typedef State *State_pointer;
#endif
在Ubuntu的g++ 4.8
中,我收到以下错误:
$ 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
我在课堂上问他这个问题,他说这是有效的C ++,它应该有效。我之前从未见过这种类实例化,它必须从字符串文字转换为std::string
,然后将其转换为State
对象。
我的教授接着指出,还有其他等效的调用非常接近:
State y = "s2"; // Does NOT compile
State y("s2"); // Does compile
State y = string("s2"); // Does compile
这里发生了什么?为什么第一个不编译,但第二个和第三个呢?同样,我的教授错误地说第一个陈述应该有效吗?或者这是编译器具体的行为?