我的教授给出了以下代码:

Main.cpp

#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


这里发生了什么?为什么第一个不编译,而第二个和第三个呢?同样,我的教授是否误以为第一句话应该起作用?还是特定于编译器的行为?

最佳答案

看来您的State对象具有采用string的构造函数。文字"s2"const char [3]类型。这就是为什么您收到错误。

它也是特定于编译器的。以下代码段适用于VS2013,但不适用于G++

struct State
{
    State(string s) { }
};

int main() {
    State s = "a";
}

10-04 13:42