【发布时间】:2013-05-28 11:53:03
【问题描述】:
我正在教我儿子 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
main.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
Jason.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!
【问题讨论】:
-
您使用的是reserved identifier。至于区别,stackoverflow.com/questions/12135498/…。也可以直接打印
std::strings,不需要c_str。 -
你能指出保留的标识符吗?另外,我有很多使用 c_str() 的习惯,但我不知道为什么。但我总是这样做。这是一个坏习惯吗?原因?
-
你还有一个 ytpo:
sd::string s应该是std::string s。 -
您的保留标识符是
__JASON_H__。c_str有它的用途,但它只是额外的代码,在这里没有任何好处。除非你真的需要一个 C 字符串,否则为什么要转换它呢? -
@Jason,是的,详细信息在我的第一个链接中概述得非常清楚。
标签: c++ gcc c++11 compiler-errors g++