-1

我正在教我儿子 C++,他想看看 C++ 11 的新特性。我将 gcc 4.8 编译为 g++-4.8

$ gcc-4.8
gcc-4.8: fatal error: no input files
compilation terminated.

运行一个简单的示例失败:

$ g++-4.8 -Wall main.cpp Jason.h Jason.cpp -o jason
main.cpp: In function ‘int main()’:
main.cpp:15:2: error: ‘Jason::Jason’ names the constructor, not the type
  Jason::Jason j1 = new Jason::Jason();
  ^
main.cpp:15:15: error: expected ‘;’ before ‘j1’
  Jason::Jason j1 = new Jason::Jason();
           ^
main.cpp:15:38: error: statement cannot resolve address of overloaded function
  Jason::Jason j1 = new Jason::Jason();
                                  ^
main.cpp:17:2: error: ‘j1’ was not declared in this scope
  j1.sayHi("Howdy");
  ^
Jason.cpp:12:19: error: expected initializer before ‘sayHi’
 void Jason::Jason sayHi(sd::string s)

我做了:g++-4.8 -Wall main.cpp Jason.h Jason.cpp -o jason

主.cpp:

#include "Jason.h"

#include <iostream>
#include <string>

int main()
{
    std::cout << "Hi" << std::endl;

    std::string s = "testing";

    std::cout << "s: " << s.c_str() << std::endl;

    Jason::Jason j1 = Jason::Jason();

    j1.sayHi("Howdy");

    return 0;
}

杰森.h:

#ifndef __JASON_H__
#define __JASON_H__

#include <iostream>
#include <string>

class Jason
{
    public:
        Jason();
    virtual ~Jason();

        void sayHi(std::string s);

    protected:
        std::string hi; 

};
#endif

杰森.cpp:

#include "Jason.h"

Jason::Jason()
{
    hi = "Hello";

    std::cout << "You said Hi like: " << hi.c_str() << std::endl;   
}

void Jason::Jason sayHi(sd::string s)
{
    std::cout << "You also said hi by: " << s.c_str() << std::end;
}

我退后一步,尝试使用系统默认的 gcc:

$ g++
i686-apple-darwin11-llvm-g++-4.2: no input files

$ g++ -Wall main.cpp Jason.h Jason.cpp -o jason

但我仍然收到一个错误:

Jason.cpp:12: error: expected initializer before ‘sayHi’

谁能帮我理解为什么会失败?

我尝试了一个简单的 C++v11 示例:

#include <iostream>
#include <thread>

//This function will be called from a thread
void call_from_thread() {
   std::cout << "Hello, World!" << std::endl;
}

int main() {
   //Launch a thread
   std::thread t1(call_from_thread);

    //Join the thread with the main thread
    t1.join();

    return 0;
}

编译..

$ g++-4.8 -Wall main2.cpp  -o test -std=c++11
$ ./test
Hello, World!
4

1 回答 1

4

多种原因,里面有很多小错别字;

void Jason::Jason sayHi(sd::string s)

应该

void Jason::sayHi(std::string s)

...和...

std::cout << "You also said hi by: " << s.c_str() << std::end;

...应该...

std::cout << "You also said hi by: " << s.c_str() << std::endl;

...和...

virtual ~Jason();

...已声明,但未实施

...和...

Jason::Jason j1 = Jason::Jason();

虽然它显然可以编译,但可以简化为(感谢克里斯)

Jason j1;

这应该让你开始,我没有 C++ 编译器来测试所以可能不是全部:)

于 2013-06-01T22:46:55.637 回答