使用指针 C++ 时出现错误消息
error message when using pointers c++
#import <iostream>
using namespace std;
main()
{
int andy = "25";
int andy1 = * andy;
int andyand = & andy;
cout <<"hello"<<endl<<andy<<endl<<andy1<<andyand;
};
我刚刚开始使用 C++ 中的指针,我不明白为什么我会得到这些: 错误:从"常量字符*"到"整数"的转换无效 错误:一元 '' 的类型参数无效(有 'int'(| 和 错误:从"int"到"int"的转换无效
首先,在C++中,您不应该使用"原始"指针。
现在,关于您的问题:错误消息说:"从 const char* 到 int 的转换无效"。
int andy = "25";
"25"
是一个字符串文本(类型为 const char*
(。您需要一个整数常量:
整数安迪 = 25;
现在 - andy
不是指针,所以你不能应用*
运算符 - 这就是你第二个错误的原因(invalid type argument of unary '*'
(。
最后,阅读一本书或有关这些的教程,因为您没有在代码中的任何位置使用指针,您只是盲目地使用 &
和 *
运算符。
这可能是使用指针的示例:
int andy = 25;
int *andy1 = &andy; // andy1 is the pointer - see star after type declaration
// with &andy we're assigning the address of andy variable to it
int andyand = *andy1; // star before pointer is dereferencing - reads the value of the memory
// address where pointer is pointing to. So, *andy1 evaluates to 25
cout << "hello" << endl << andy << endl << *andy1 << andyand;
哦,除了我之外,每个人都注意到了这一点——不幸的是(对你和我们来说(,C++没有import
指令——但它应该在几年内与我们同在。
这里有很多
无效的语法:
#import <iostream> // WRONG!
using namespace std;
main()
{
int andy = "25"; // Not good
int andy1 = * andy; // not good
int andyand = & andy; // not good
cout <<"hello"<<endl<<andy<<endl<<andy1<<andyand;
}
你应该拥有的是:
#include <iostream>
using namespace std;
main()
{
int andy = 25; // 25 is an int, "25" is a char*
//int andy1 = *andy; // andy is not a pointer, so you cannot dereference it
int* andyand = &andy; // andyand now points to andy
cout <<"hello"<<endl<<andy<<endl<<*andyand;
}
哪个将打印出来
hello
[value of andy]
[value of andy]
C++中没有 #import 指令。我想你的意思是
#include <iostream>
函数主应具有返回类型 int。
指定整数文本时不带引号。所以而不是
int andy = "25";
应该写
int andy = 25;
还有这些声明
int andy1 = * andy;
int andyand = & andy;
无效。目前尚不清楚您要定义什么。
只需写:
using namespace std;
main()
{
int andy = 25; // no quotation marks
int* andy1 = &andy; // use "&" to take the addrees of andy for your pointer
int* andyand = & andy;
cout <<"hello"<<endl<<andy<<endl<<andy1<<endl<<andyand;
};
无需对整数变量使用引号。
相关文章:
- C++错误消息*成员参考.**初学者*
- 如何通过参数抛出错误消息
- glad 导致 glfwSwapBuffers 返回错误消息
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- 如何接受 [ENTER] 键作为无效输入并发送错误消息
- 重新定义预定义的 errno 错误消息 (E2BIG)
- SDL 映像:无法打开映像,仅显示错误消息
- 错误消息:使用"string* +="后"no match for 'operator+='"
- 错误消息"expected expression"....有人知道它为什么这么说吗?
- 在 Eclipse: "error: no match for 'operator='" 中获取错误消息
- GCC 警告和 gcc 错误消息之间的区别
- 为 c++ cin 上的输入数无效生成错误消息
- 来自带有mbedtls TLS的Mongoose Web服务器的错误消息
- 如何使用realsense摄像头调试ROS错误消息
- C++ 概念 - 需要括号中的概念会导致 2 条冲突的错误消息
- 编译器收到错误消息(textc.exe已停止)
- 结构数组的构造函数错误,错误消息:没有构造函数实例与参数列表匹配
- 使用 c++/WinRT Direct3D UWP Game DR 模板 Direct X11 的错误消息
- max_element() 给出非常奇怪的错误消息
- 不断收到错误消息,并非所有控制路径都返回值