I was practicing using the auto
and decltype
keywords.
我正在练习使用auto和decltype关键字。
When I tried to add 2 values and print the result, I got 60603 (Fedora Cygwin 5.4.0-2) in the console.
当我尝试添加2个值并打印结果时,我在控制台中得到了60603(Fedora Cygwin 5.4.0-2)。
I'm think that's probably the name of my compiler, right? Why did I get that? Because that's pretty confusing, as I'm only a rookie to the C++ world.
我认为这可能是我的编译器的名称,对吧?我为什么这样做?因为那令人困惑,因为我只是C ++世界的新秀。
Here's the complete code:
这是完整的代码:
#include <iostream>
template<class T, class K>
auto test(T val1, K val2) -> decltype(val1 + val2) {
return val1 + val2;
};
int main() {
std::cout << test("Hello There! ", 99);
return 0;
}
Thanks for your time! And Please tell me a way to get this to actually print out Hello There! 99
谢谢你的时间!请告诉我一种方法来实现打印Hello Hello! 99
1 个解决方案
#1
0
When you pass the constant string literal "Hello There!"
to your function you will pass a pointer to the first character in that string.
当您传递常量字符串文字“Hello There!”时对于您的函数,您将传递指向该字符串中第一个字符的指针。
The type of a pointer plus an integer is a pointer, so the function returns a pointer. More precisely it returns a pointer to the 99:th element of the string literal, and since the string doesn't have 99 elements you are way out of bounds and have undefined behavior.
指针的类型加上一个整数是一个指针,因此该函数返回一个指针。更确切地说,它返回一个指向字符串文字的第99个元素的指针,并且由于字符串没有99个元素,因此您将超出边界并具有未定义的行为。
#1
0
When you pass the constant string literal "Hello There!"
to your function you will pass a pointer to the first character in that string.
当您传递常量字符串文字“Hello There!”时对于您的函数,您将传递指向该字符串中第一个字符的指针。
The type of a pointer plus an integer is a pointer, so the function returns a pointer. More precisely it returns a pointer to the 99:th element of the string literal, and since the string doesn't have 99 elements you are way out of bounds and have undefined behavior.
指针的类型加上一个整数是一个指针,因此该函数返回一个指针。更确切地说,它返回一个指向字符串文字的第99个元素的指针,并且由于字符串没有99个元素,因此您将超出边界并具有未定义的行为。