2014-05-10 254 views
-7

如果函数是在C++中这样定义:这是什么意思?

char *Func() { 

return "Text"; 
} 

然后;

Func()[] = 'a'; 

意思是什么?

+1

_'Means什么? '_你很容易失败,无论你试图用这个做什么! –

+2

这意味着什么,因为编译器错误会告诉你,如果你试图编译它。 –

+0

这个问题已经在面试中问过了,我不知道什么是意思。函数如何创建数组? – Rohit

回答

7

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

我不知道Func()[] = 'a';的意图是什么。 C++编译器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'; 
+0

它可能想知道,如果你知道代码是无效的,为什么... – Massa

+0

这将是很好的概述为什么这个片段是注定要失败,因为这是一个答案 – user2485710

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) 
+0

原始片段不使用任何索引'[]'运算符。 – user2485710

+0

我知道。没有索引它根本不会编译。 –