这意味着什么?

What is means of this?

本文关键字:什么 意味着      更新时间:2023-10-16

如果函数在c++中是这样定义的:

char *Func() {
 return "Text";
}

,

Func()[] = 'a';

意味着什么?

这可能意味着面试官想测试你面对无效源代码的反应。

我不知道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';

一旦你得到它编译(只是)像这样:

#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)