【发布时间】:2019-10-28 20:16:46
【问题描述】:
我的 c++ 程序是这样的:
#include <iostream>
#include <cstdlib>
#include <dos.h>
using namespace std;
void arr(int pts,string *splt_msg){
for(int x=-1;x<pts-1;x++){
string input;
cout<<"Enter part "<<x<<endl;
cin>>input;
(*splt_msg)[x]=input;
}
}
void print_arr(string *splt_msg,int del,int parts){
for(int x=-1;x<parts-1;x++){
cout<<(*splt_msg)[x];
delay(del);
}
}
int main(){
cout<<"Parts in message: ";
int parts;
cin>>parts;
cout<<"Delay between parts(ms): ";
int del;
cin>>del;
parts--;
string splt_msg[parts];
string (*Parr)[parts]=&splt_msg;
arr(parts,Parr);
print_arr(Parr,del,parts);
return 0;
}
这是错误代码(在 windows 和 mingw 上):
c:\Users\User\Desktop\c++>g++ -o program test1.cpp
In file included from test1.cpp:3:0:
c:\mingw\include\dos.h:54:2: warning: #warning "<dos.h> is obsolete; consider using <direct.h> instead." [-Wcpp]
^~~~~~~
test1.cpp: In function 'void arr(int, std::__cxx11::string*)':
test1.cpp:18:14: error: 'delay' was not declared in this scope
delay(del);
^
test1.cpp: In function 'int main()':
test1.cpp:32:17: error: cannot convert 'std::__cxx11::string (*)[parts] {aka std::__cxx11::basic_string<char> (*)[parts]}' to 'std::__cxx11::string* {aka std::__cxx11::basic_string<char>*}' for argument '2' to 'void arr(int, std::__cxx11::string*)'
arr(parts,Parr);
^
test1.cpp:33:27: error: cannot convert 'std::__cxx11::string (*)[parts] {aka std::__cxx11::basic_string<char> (*)[parts]}' to 'std::__cxx11::string* {aka std::__cxx11::basic_string<char>*}' for argument '1' to 'void print_arr(std::__cxx11::string*, int, int)'
print_arr(Parr,del,parts);
^
有人知道我做错了什么以及解决方案吗? 感谢您的帮助,我只是想编写一个简单的程序来测试一些概念,例如将指针传递给函数,但它似乎不起作用。
【问题讨论】:
-
这行应该是什么意思
string (*Parr)[parts]=&splt_msg;?说真的,我不知道 -
@foreknownas_463035818 这是指向
std::string的指针的 VLA 的声明,称为Parr。绝对不是他们想要的。 -
注意有关 dos.h 已过时的警告。
delay函数几十年前就消失了。查看std::this_thread:::sleep_for寻找现代替代品。 -
你从哪里定义或包含
string的定义? -
如果你想学习指针,最好使用实际需要指针的示例。无需在您的代码中使用它们。虽然,从我的脑海中,我不知道需要原始指针的东西的好例子,我不记得我上次使用的时候......确实有更重要的东西要学习