如果函数在C ++中定义如下:
char *Func() {
return "Text";
}
然后;
Func()[] = 'a';
意味着什么?
答案 0 :(得分:7)
这可能意味着面试官想要测试您对面对无效源代码的反应。
我不知道Func()[] = 'a';
的意图是什么。 C ++编译器clang 3.4输出以下内容:
a.cc:3:9: warning: conversion from string literal to 'char *' is deprecated
[-Wc++11-compat-deprecated-writable-strings]
return "Text";
^
a.cc:6:1: error: C++ requires a type specifier for all declarations
Func()[] = 'a';
^~~~
a.cc:6:5: error: function cannot return array type 'int []'
Func()[] = 'a';
答案 1 :(得分:1)
一旦你按照这样编译(只是):
#include <iostream>
char *Func() {
return "Text";
}
int main() {
std::cout << Func() << std::endl;
Func()[0] = 'P';
std::cout << Func() << std::endl;
return 0;
}
你明白了:
Compiling the source code....
$g++ -std=c++11 main.cpp -o demo -lm -pthread -lgmpxx -lgmp -lreadline 2>&1
main.cpp: In function ‘char* Func()’:
main.cpp:5:9: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
return "Text";
^
Executing the program....
$demo
Text
Segmentation fault (core dumped)