C ++ - 混淆了教授的类实例化的特定例子

时间:2014-04-24 00:08:55

标签: c++ class instantiation

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

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;
}

State.h

#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

这里发生了什么?为什么第一个不编译,但第二个和第三个呢?同样,我的教授错误地说第一个陈述应该有效吗?或者这是编译器具体的行为?

1 个答案:

答案 0 :(得分:2)

看起来你的State对象有一个带string的构造函数。文字"s2"const char [3]类型。这就是您收到错误的原因。

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

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

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