public static <T> T foo(T x, T x2) {
return (T) (x + " " + x2);
}
public static void main(String args[]) {
System.out.println(foo(33, "232"));
}
Run Code Online (Sandbox Code Playgroud)
我知道T会成为参数中传递的类型.但这里有两种类型.哪一个是T?
当我调用foo时,编译器为什么不强迫我拥有相同类型的参数?
带有while循环的第一个函数:
public static double sum(int n){
double sum = 0;
while (n!=0){
sum+=1.00/((2*n-1)*(2*n+1));
n--;
}
return sum;
}
Run Code Online (Sandbox Code Playgroud)
相同的功能,但for循环提供了另一种解决方案.
public static double sum1(int n){
double sum = 0;
for (int i=1;i<=n;i++){
sum+=1.00/((2*n-1)*(2*n+1));
}
return sum;
}
Run Code Online (Sandbox Code Playgroud)
函数计算系列:
1 /(1*3)+ ... + 1 /((2n + 1)*(2n-1))
由于某种原因,使用for循环的函数使得和越来越小而while函数工作正常.
为什么for循环解决方案不起作用?
我有这个功能:
template <typename T, T sep>
void split (){
std::cout << sep << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试使用此命令调用它时:split<'f'>();
我收到以下错误:
q3.cpp: In function ‘int main()’:
q3.cpp:36:16: error: no matching function for call to ‘split()’
split<'f'>();
^
q3.cpp:36:16: note: candidate is:
q3.cpp:31:6: note: template<class T, T sep> void split()
void split (){
^
q3.cpp:31:6: note: template argument deduction/substitution failed:
Run Code Online (Sandbox Code Playgroud)
为什么?
请考虑以下代码:
const char* text = "hi";
printf("%s\n",text);
printf("%p\n", &text);
printf("%p\n", text);
Run Code Online (Sandbox Code Playgroud)
每个人从哪里printf获取它打印的价值?
有什么区别?
我有2个头文件相同的头文件:
template<typename T> inline void func(){
}
Run Code Online (Sandbox Code Playgroud)
我在main.cpp文件中包含这两个头文件然后编译:
g++ main.cpp -o run
Run Code Online (Sandbox Code Playgroud)
但我得到:
In file included from main.cpp:2:0:
test2.cpp:1:34: error: redefinition of ‘template<class T> void func()’
template<typename T> inline void func(){
^
In file included from main.cpp:1:0:
test.cpp:1:34: error: ‘template<class T> void func()’ previously declared here
template<typename T> inline void func(){
Run Code Online (Sandbox Code Playgroud)
如果使用可以重新定义的内联函数,我会得到什么错误?