使用指针 C++ 时出现错误消息

error message when using pointers c++

本文关键字:错误 消息 指针 C++      更新时间:2023-10-16
#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;
};

无需对整数变量使用引号。